Monday, February 20, 2012

Replace ="Text” with =\"Text\” using Preg_Replace


I would like to replace the following:



="Dark4Red"



with



=\"Dark4Red\"



The = sign and double quotations are fixed ="..." I just need to add slashes before double quotations.




$content = preg_replace('/="[^a-zA-Z#0-9]"/', '=\"[^a-zA-Z#0-9]\"', $line);



The above solution didn't work. Any idea?

2 comments:

  1. How about addslashes?

    That aside, you appear to have not read any of the examples on preg_replace's manual page - if you had, you'd have known that you capture a subpattern (in this case the contents of the quotes) with parentheses and use $1 to put them in the replacement string.

    ReplyDelete
  2. You can use

    $str = '"Text"';
    str_replace('"','\"', $str);

    ReplyDelete