문제

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);
도움이 되었습니까?

해결책

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

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top