Question

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);
Was it helpful?

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);

OTHER TIPS

Create a backreference to the characters by wrapping them in a group. Then use $1 to refer to the contents of the first group.

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

Also, you'll probably want (MTM|SIR|FDF|TAA) instead of [MTM|SIR|FDF|TAA]{3}. This means you must have either MTM, SIR, FDF or TAA.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top