Jump to content

preg_replace help


afrojojo

Recommended Posts

I have this code that I used to remove all image tags from a string.

 

$pattern = '/<img[^>]+>/is';
$body = preg_replace($pattern, '', $body);

 

How would I change the pattern to cut everything out of the string($body) after it sees "--". Would like to cut out the "--" as well.

Link to comment
Share on other sites

Can we see an example input with expected output please, that always helps immensely with with Regex as it can be difficult to decipher exactly what your after. At it's simplest you would be looking at something along the lines of...

 

'#--.*$#'

 

but I don't really see how that bares any relation to the pattern you say you already have.

Link to comment
Share on other sites

preg_replace('#-{2,}.*$#', '', $input);

Should work to a certain degree. You have a blank line in your first example which is located before the --, yet you don't seem to want it in the output. Your best bet will probably be to call trim on the result of the preg_replace. It will replace anything after 2 or more dashes.

Link to comment
Share on other sites

Oops, I forgot the s modifier. I should point out though that other than that the pattern is essentially the same as the one suggested by premiso. Placing the dash in a character class will make no difference, the quantifier will be applied to it regardless. Creating the brackets around it to create a capture group is not really achieving anything, since they go around the whole pattern you are simply making $1 an exact copy of $0, and we aren't even using a back-reference in either the pattern or the replacement anyway. Since .* is a 'greedy' match and the . is a catch all assertion (when you remember the s modifier :)) it should always match to the end thus meaning the dollar sign I included is probably not required either.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.