0

I have i string in my PHP-code which looks like this

Bokad av Anna Göransson 14:45 - 15:45

Now i want to replace "Anna" with "A.". How can i do that using regexp and PHP?

4
  • 1
    Why do you think you need regular expressions for this simple str_replace? Commented Jan 31, 2012 at 21:02
  • 1
    How do you tell what the first name is? Commented Jan 31, 2012 at 21:08
  • 1
    Is that just an example string? If so you need to elaborate on the 'rules' of the contents of the string for us to be able to help you. Commented Jan 31, 2012 at 21:09
  • old.kalzumeus.com/2010/06/17/… Commented Jan 31, 2012 at 22:40

2 Answers 2

2

You can use something different if the string is dynamic and subject to change.

$string = "okad av Anna Göransson 14:45 - 15:45";
$names = explode(" ",$string);
$names[2] = strtoupper($names[2][0]).".";
$string = implode(" ",$names);
Sign up to request clarification or add additional context in comments.

3 Comments

strtoupper(substr($names[2],0,1))."."; can also be written as strtoupper($names[2][0]).".";
To clarify what Braveyard said: this solution relies upon the name in question (Anna) being the 3rd word (array index 2). In my limited experience, there are always cases where this won't be true.
@FrankFarmer : You're right, thanks for the tip.I will update my answer .
0

You can do use something like this

$foo=str_replace('Anna', 'A',$foo);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.