MichaelBS
MichaelBS

Reputation: 15

How to use preg_replace to replace everything within slashes? (Only every other match is replaced)

I am new to regular expressions, and I've been trying to use it with an url, but I can't get it to work.

I have a string that is:

/plugins/plugins/plugins/plugins/plugins/plugins/

and I would like to replace all letters to the string "{char}" so that the string end up being:

/{char}/{char}/{char}/{char}/{char}/{char}/

I've tried this:

<?php
    $pattern        = '#(/)([a-z\_]+)(/)#'; 
    $replacement    = '$1{char}$3'; 
    $string         = '/plugins/plugins/plugins/plugins/plugins/plugins/';

    echo preg_replace($pattern, $replacement, $string);
?>

But this code is resulting in this:

/{char}/plugins/{char}/plugins/{char}/plugins/

What am I doing wrong?

Upvotes: 1

Views: 344

Answers (1)

Michael Low
Michael Low

Reputation: 24506

The problem is your regex is matching /plugins/ - matching slashes at both the front and the end. Each letter is only matched by the regex once, so if a slash is matched at the end of one word it can't also be counted as the start of another. Hence, it's only matching every other one.

Try this instead:

<?php
    $pattern        = '#(/)([a-z\_]+)(?=/)#'; 
    $replacement    = '$1{char}'; 
    $string         = '/plugins/plugins/plugins/plugins/plugins/plugins/';

    echo preg_replace($pattern, $replacement, $string);
?>

It works by using lookahead, instead of actually matching the final slash (and "consuming" it) it just checks to make sure it's there.

Upvotes: 3

Related Questions