2

I want to use a regexp in my str_replace, i suppose the correct solution to this would be to use preg_replace but i don't know how to use that. Anyway i want to turn src= into the character a if it matches src= or if it has any spaces in between src and =. Normally to just turn src= it'd be:

$string = str_replace('src=', 'a', $string);

But the problem is that wouldn't work when there are space(s) between src and =. This is why i need to use a regexp. Thanks for any help.

1
  • That's why php.net/manual/en/function.preg-replace.php exists :) For future reference, always remember to Google first, a query for regexp in php str_replace will take you right there. Commented Aug 20, 2013 at 21:48

3 Answers 3

1
$string = preg_replace('/src\s*=/i', 'a', $string);

What that RegEx means is "match src followed by 0 or more spaces followed by =".

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

4 Comments

if there is no whitspace, this fails. use * instead of +. Second, = is no special char, so no escaping required.
@dognose Corrected it.
@Campari Nice, just one more tweak. How can i make src case insensitive?
@BobSm Sure. The i modifier at the end makes the RegEx case insensitive.
0

preg_replace just works as str_replace:

$new_string = preg_replace($pattern, $replacement, $old_string);

The pattern in your case would be "@src\s*=@i" (\s* covers zero to infinite whitespaces, @ is just one out of different possible delimeters the pattern requires, i (after the last delimiter) makes the pattern case insensitive.)

Comments

0

Use preg_replace and the following pattern:

src(?:\s+)?=

Split this up:

  • src obviously finds the "src" part
  • (?:\s+)? finds 0 or more space(s)
  • = to finish it off, finds the "="

So altogether, it would be:

$new_string = preg_replace("/src(?:\s+)?=/i", 'a', $string);

Hope this helps!

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.