#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2009
    Posts
    6
    Rep Power
    0

    Question Need help with preg_replace


    Hello,
    I trying to add checked="checked" to the input which value x.
    find '<input'.anything here.'value="'.value.'"'.anything
    replace '<input' with <input checked="checked"

    here is what I end up with:
    Code:
    //text in which preg_replace must find input
    $v = 'some text<input name="something1" type="checkbox" value="123" />something here<br><br><input name="something2" type="checkbox" value="122" /><br>';
    $output = preg_replace('/<input(.*?value="123" .*?)\s/','<input checked="checked"$1',$v,1);
    echo $output
    result:
    some text<input checked="checked" name="something1" type="checkbox" value="123" />somethinghere<br><br><input name="something2" type="checkbox" value="122" /><br>
    expected result:
    some text<input checked="checked" name="something1" type="checkbox" value="123" />something here<br><br><input name="something2" type="checkbox" value="122" /><br>

    Any ideas how to fix that?
    Thanks.
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    May 2007
    Posts
    765
    Rep Power
    929
    You're problem is the regex has a \s on the end that isn't included in the capture, so it is removed from the string and not replaced.

    A better solution is not to match more than you care about. The look ahead makes sure that value="123" appears, but doesn't include it in the match.
    Code:
    /<input(?=.*value="123")/
    The best solution would be to parse the markup and make your changes to the tree structure. The regex will get confused with input like:
    Code:
    <input/> value="123"
    <input value="wrong"/> <input value="123"/>

    Comments on this post

    • ishnid agrees
    sub{*{$::{$_}}{CODE}==$_[0]&& print for(%:: )}->(\&Meh);
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2009
    Posts
    6
    Rep Power
    0
    Thank you for quick reply, well the value will be only filled with inputs so markup will be clean, however speed is important, i just found what
    preg_replace('|value="'.$i.'"|','value="'.$i.'" checked="checked"',$v,1);
    is three times quicker than
    preg_replace('/<input(?=.*value="123")/','<input checked="checked"$1',$v,1);

IMN logo majestic logo threadwatch logo seochat tools logo