4

I have this regular expression, I would like it to remove all text between $ and $ and replace it with an empty string, UNLESS there is a space anywhere between the two $ signs, and in that case ignore the replacement. With the regexp that I have now, it removes it no matter if there is a space or not.

<?php
$tmp = "<p>
    $random_text$
</p>
<p>
    $random text2$
</p>
<p>
    This is some text
</p>
<p>
    This is some text
</p>";

$tmp = preg_replace("/\\$[^ ].+?\\$/", "", $tmp);

So, in the end I would like to have this as the output. As you may notice, the text between the first paragraph tags are gone, but second one still stands.

<p>

</p>
<p>
    $random text2$
</p>
<p>
    This is some text
</p>
<p>
    This is some text
</p>

2 Answers 2

1
/\\$[^ ]+?\\$/

I've just removed the dot

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

4 Comments

This will just remove a single non-space character.
@RyanNaddy only one space is ok?
1+, but this seem to cover that.
Sorry, I wasn't thinking earlier. This should work. Though it might be preferable to put $ in the negative character class as well, to ensure that you are matching consecutive occurrences of $.
0
<?php $source = 'His $name$ is $Luis$';
echo $result = preg_replace('/\$(.*?)\$/', '<b>$1</b>', $source);
?>

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.