Search code examples
phpregexfunctionreplacetargeting

Does preg_replace use a regular expression to target, or some other format?


I am trying to replace all occurrences of one ot the groups of three letters (in capital) followed by 5 numbers (0-9) and then replace them with a link. Nothing I've done so far seems to work. This is what I have at the moment.

return preg_replace("(MTM|SIR|FDF|TAA)[0-9]{5}", "<a href='$&'>$&</a>", $str);

Solution

  • You don't need to have a capturing group in your case since you can refer to the whole pattern with $0. And you must add delimiters to your pattern:

    $str = preg_replace('~(?>MTM|SIR|FDF|TAA)\d{5}~', '<a href="$0">$0</a>', $str);