Why is this preg_replace not working?

Discussion in 'PHP' started by mark_s, Mar 19, 2009.

  1. #1
    I want every instance of "</q></span>" to change to "</q>".

    Example page: http://www.murraysworld.com/news/article/13518/

    I tried lots of variations of this but it just adds loads of quote tags all over the place:
    $article['body'] = preg_replace("/(<\/q><\/span>)/", "</\q>", $article['body']);
    Code (markup):

     
    mark_s, Mar 19, 2009 IP
  2. SmallPotatoes

    SmallPotatoes Peon

    Messages:
    1,321
    Likes Received:
    41
    Best Answers:
    0
    Trophy Points:
    0
    #2
    $article['body'] = preg_replace('`</q></span>`', '</q>', $article['body']);
    Code (markup):
    You were making things more complicated than necessary in several ways:
    1) Using parentheses; they aren't necessary unless you need to use the matched string in the replace part.
    2) Using double-quotes; they complicate backlashes.
    3) Using slash to contain your regular expression when you are matching on slashes. You could escape them, but it's easier to just use a different container character. I used backticks in this case.

    Actually, in this case, str_replace is faster and easier:
    $article['body'] = str_replace('</q></span>', '</q>', $article['body']);
    Code (markup):
    But I'm leaving in the preg solution out of general informativity.
     
    SmallPotatoes, Mar 19, 2009 IP
  3. mark_s

    mark_s Peon

    Messages:
    497
    Likes Received:
    10
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thanks for your help on this... what you kindly have done for me completes the simple solution to my problem but ideally, if you have the time, I'd want it so every instance of this:

    <span class="more_intro"><a href="javascript:void(0)" class="more" onclick="dsp(this)">THIS TEXT WILL BE DIFFERENT ON EACH PAGE</a></span><span style="display: block;" class="more_content"><q>
    Code (markup):
    Is replaced with:

    THIS TEXT WILL BE DIFFERENT ON EACH PAGE:<br /><br /><q>
    Code (markup):
    The text inside will change all the time so the preg_replace will some how need to ignore what the text is specifically and instead just take notice of the HTML code around it.

    Is that possible? Sorry for asking so much.
     
    mark_s, Mar 19, 2009 IP