JayGatz
JayGatz

Reputation: 271

Regex to replace one string with another in PHP

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 '%' ?

Upvotes: 1

Views: 392

Answers (5)

Ja͢ck
Ja͢ck

Reputation: 173522

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.

Upvotes: 0

itsmejodie
itsmejodie

Reputation: 4228

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.

Upvotes: 0

Mike Perrenoud
Mike Perrenoud

Reputation: 67898

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.

Upvotes: 0

nhinkle
nhinkle

Reputation: 1157

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.

Upvotes: 2

Robbert
Robbert

Reputation: 6582

You should look into preg_replace. For your question

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

Upvotes: 1

Related Questions