Match regular expression then replace within string

Discussion in 'PHP' started by Silver89, Sep 23, 2011.

  1. #1
    I have a small exert of text that I want to check for an item within an array and then put strong tags around that item, here is what I'm trying so far in php but I don't think the match part is working?

    
    $text = "10 euro is the cost";
    
    $patterns = array("pounds", "euro", "dollar");
    
    $found = preg_match("/^([0-9]+) ".$patterns."/", $text);
    
    echo str_replace($found, "<strong>".$found."</strong>", $text);
    
    // Should echo <strong>10 euro</strong> is the cost
    
    PHP:
    Any ideas on what's not correct above?

    Thanks
     
    Silver89, Sep 23, 2011 IP
  2. jazzcho

    jazzcho Peon

    Messages:
    326
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    0
    #2
    $paterns is an array and not a string

    Use a foreach structure to loop and you 're good.
     
    jazzcho, Sep 23, 2011 IP
  3. Silver89

    Silver89 Notable Member

    Messages:
    2,243
    Likes Received:
    72
    Best Answers:
    0
    Trophy Points:
    205
    #3
    Concerning processing would it be better to do the foreach item in array or just make the it non dynamic and use:

    ([item1|item2|item3|item4]+)
    Code (markup):
    If it's for about 30 items?
     
    Silver89, Sep 23, 2011 IP
  4. jazzcho

    jazzcho Peon

    Messages:
    326
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    0
    #4
    It 's too little difference for 30 items anyway. Do it with foreach, because it 's more readable.
     
    jazzcho, Sep 23, 2011 IP
  5. gvre

    gvre Member

    Messages:
    35
    Likes Received:
    6
    Best Answers:
    3
    Trophy Points:
    33
    #5
    Try this
    $text = "10 euro is the cost";
    $patterns = array("pounds", "euro", "dollar");
    $replacements = array();
    foreach($patterns as &$p)
    {
            $replacements[] = "<strong>$p</strong>";
            $p = '#' . $p . '#';
    }
    $s = preg_replace($patterns, $replacements, $text);
    
    Code (markup):
     
    gvre, Sep 24, 2011 IP