mikepreble
mikepreble

Reputation: 269

PHP Preg_replace: can't get the replace part to work, finding is fine

I don't know how to do the following:

find all instances of '/\s[2-9]\)/' and replace the space with a <br /> tag.
Something as simple as this doesn't work:

$preg_num = ' /\s[2-9]\)/';
$preg_fix = "'/<br>/[2-9]\)'";
preg_replace($preg_num,$preg_fix,$notes);

What do I need to change the $preg_fix variable to?

Upvotes: 0

Views: 155

Answers (2)

agent-j
agent-j

Reputation: 27943

Using a lookahead is simpler than a backreference, IMHO.

$preg_num = '/\s(?=[2-9]\))/';
$preg_fix = '<br/>';
preg_replace($preg_num,$preg_fix,$notes);

This way, you are only replacing the space with the <br/>.

Upvotes: 3

Jon Gauthier
Jon Gauthier

Reputation: 25592

The replacement string is not treated as a regex — it is more like a literal string. If you are trying to put whatever digit [2-9] that was matched in the original regex into the replacement string, capture the character as a group and use a backreference.

$preg_num = '/\s([2-9])\)/';
$preg_fix = "<br />$1)'";
preg_replace($preg_num,$preg_fix,$notes);

For more information:

Upvotes: 2

Related Questions