bart
bart

Reputation: 13

Strange Replacement in Regular Expression

Why doesn't this work (in php)?

$string=" https://youtu.be/g434EnjOOuU ";

$result=preg_replace("@https?://youtu.be/([a-z0-9-_]*)@isU","[YOUTUBE]$1[/YOUTUBE]",$string);

Result = [YOUTUBE][/YOUTUBE]g434EnjOOuU

Instead of: [YOUTUBE]g434EnjOOuU[/YOUTUBE]

I just can't figure out what the replacement comes at the end of the string instead of at the right place.

Thanks!

Upvotes: 1

Views: 26

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626896

Remove the U PCRE_UNGREEDY modifier that makes * to act as a lazy quantifier. When a lazily quantified pattern appears at the end of the pattern it usually matches an empty string.

See the fixed regex demo.

Upvotes: 1

Related Questions