Search code examples
phpregexpreg-replacepreg-matchspecial-characters

preg_match(): Compilation failed: unrecognized character


Sorry for my english.

$string = "product#[:id]#[:str]";

$regex = preg_replace("/\[:(\w+)\]/", "(?<$1>.+?)", $string);

What I get is product#(?.+?)#(?.+?) instead of product#(?<id>.+?)#(?<str>.+?)

I want to do that because I need preg_match() to create key names in $matches:

preg_match('/^'. $regex .'$/', str_replace("/", "#", self::$path), $matches)

The point is, it works without '<' and '>'. But I need them for next code. So what should I do about these '<', '>' chars? I need them but don't know what to do. I also tried to escape them: \< (But no results).

Please help me if you have any ideas.

Edit:

Seems like what I did was ok. Now there's new problem:

$string = "product#[i:id]#[*:str]";

$regex = preg_replace("/\[i:(\w+)\]/", "(?<$1>[0-9]+)", $regex);
$regex = preg_replace("/\[\*:(\w+)\]/", "(?<$1>.+?)", $regex);

No I tried something else and this doesn't work. Why? :(


Solution

  • If the result of your preg_replace is to be rendered in a browser, and just this rendered result should contain < and > chars, then you should generate them as &lt; and &gt;.

    So maybe your replacement string (2nd argument of preg_replace) should be:

    (?&lt;$1&gt;.+?)