1

PHP This is an oversimplification of a problem to get to the point.

I am trying to use preg_replace() on a $string that contains a name. I want to replace an O with an E in the first name only, if there is one. So I want to stop looking when I encounter the first space. There may be multiple spaces in the full name, but I am only looking at the first part of the name.

$string = preg_replace('/O/', 'E', $string);

How do I add code to tell it to stop at the first space?

5
  • 2
    Split the string with explode(), perform the replacement on the first element, then put it back together with implode(). Commented Apr 15, 2019 at 19:15
  • There might be a way to do it in a single preg_replace() using a lookbehind, but this will be clearer. Commented Apr 15, 2019 at 19:16
  • Yes I was trying to do it with just preg_replace. I use to do that in perl telling it to search up until you hit a space [^/s]. Commented Apr 15, 2019 at 19:20
  • PHP uses PCRE, so you should be able to do it the same way. Commented Apr 15, 2019 at 19:24
  • Just change $string =~ s/xxx/yyy/ to $string = preg_replace('/xxx/', 'yyy', $string); and replace xxx and yyy with whatever you'd do in Perl. Commented Apr 15, 2019 at 19:25

2 Answers 2

1

From the php.net manual for preg_replace:

preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] ) : mixed

limit The maximum possible replacements for each pattern in each subject string. Defaults to -1 (no limit).

So for your code it would look something like this:

$string = preg_replace('/O/', 'E', $string, 1);

See the documentation for more info - PHP manual

Sign up to request clarification or add additional context in comments.

3 Comments

If there's no O in the first name, but one in the last name, this will not do what the poster requests.
There could be more than one O in the first name, so there is no limit to the number of replaces to make in the first name.
Why did you accept this answer when it's obviously not correct?
0

This worked for me.

$string = preg_replace('/O[^\s]/', 'E', $string);

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.