mrhn
mrhn

Reputation: 18926

Regex replace url encoded string

I have a string in which I want to replace the text [[signature]] with a given value, but because it is encoded, the text looks like %5B%5Bsignature%5D%5D.

How do I replace this using a regular expression? This snippet works, but only if the string is not encoded:

$replace = preg_replace('/\[\[signature\]\]/', 'replaced!', $html);

Upvotes: 1

Views: 1856

Answers (1)

BadHorsie
BadHorsie

Reputation: 14554

You have encoded the string, so just decode it then run your replace.

$html = urldecode($html);
$replace = preg_replace('/\[\[signature\]\]/', 'replaced!', $html);

You can always encode it again afterwards if you need:

$html = urlencode($html);

Non-Regex Solution

If your find/replace is really that simple then you don't even need to use regex. Just do a standard string replace:

$html = str_replace('[[signature]]', 'replaced!', $html);

Upvotes: 5

Related Questions