1

Instead of wondering what regex I need for each time I need a regex, I like to learn how to do basic string replacement with regexes.

How do you take one string and replace it with another with regexes in PHP ?

For example how do you take all '/' and replace them with '%' ?

3
  • 3
    php.net/manual/en/function.preg-replace.php Commented Jun 14, 2013 at 0:06
  • There's good documentation on the PHP website with many examples too (at the bottom of the page) Commented Jun 14, 2013 at 0:06
  • 2
    Be sure not to ignore strtr and str_replace where applicable. Regular expressions are great but not always necessary. Commented Jun 14, 2013 at 0:09

5 Answers 5

2

If you just want to do basic string replacement (i.e. replace all 'abc' with '123') then you can use str_replace, which doesn't require using regex. For basic replacements, this will be easier to set up and should run faster.

If you want to use this as a tool to learn regex though (or need more complicated replacements) then preg_replace is the function you need.

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

Comments

1

You should look into preg_replace. For your question

 $string = "some/with/lots/of/slashes";
 $new_string = preg_replace("/\//","%",$string);
 echo $new_string;

1 Comment

If you use something else than / as the delimiter, you don't have to escape it inside the expression.
0

I like to learn how to do basic string replacement with regexes.

That's a little broad for this forum. However, to answer a more specific question like:

For example how do you take all '/' and replace them with '%' ?

You could do that like this:

$result = preg_replace('#\/#', '%', 'Here/is/a/test/string.');

Here is a Rubular that proves the regex.

2 Comments

The Rubular you posted adds the delimiters for you.
My point was that you were missing the forward slashes to delimit your regular expression. The Rubular link you posted addes the forward slashes for you, but preg_replace will now. I see that you're now using #, but I'm not sure that would work in PHP.
0

Note, you are not limited to using the common / delimiter, which means when working with forward slashes it is often easier to change to a different delimiter EG.

$mystring = 'this/is/random';
$result = preg_replace('#/#', '%', $mystring);

This will make '#' the delimiter, rather than the standard '/', so it means you do not need to escape the slash.

Comments

0

I would do this simply with strtr which is very suitable for character mapping, e.g.

strtr('My string has / slashes /', '/', '%');

If you want to also replace the letter a with a dash:

strtr('My string has / slashes /', '/a', '%-');

As you can see, the second and third argument define the transformation map.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.