Question

$string = preg_replace("_\[soundcloud\]/http:\/\/soundcloud.com\/(.*)/\[/soundcloud\]_is", "<iframe width=\"100%\" height=\"166\" scrolling=\"no\" frameborder=\"no\" src=\"https://w.soundcloud.com/player/?url=\$0\"></iframe>", $string);

Hello once again Stackoverflow!

I would like my UBB parser to support soundcloud links, by parsing

[soundcloud](url)[/soundcloud]

into

<iframe width="100%" height="166" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url= (url) "></iframe>

by using the preg_replace above, but this isn't working.

Can someone please help me what is wrong with my regex?

Thanks in advance!

Était-ce utile?

La solution

Your pattern isn't well escaped.

  1. Since you use a delimiter that is not a /, you don't need to escape all the slashes. And closing square brackets don't need to be escaped:

    ~\[soundcloud]http://soundcloud.com/(.*)/\[/soundcloud]~is

  2. To capture the url you use a greedy quantifier *. It is a problem if you have more than one [soundcloud] tag in your string, because the capture will stop at the last closing tag. To solve this you can use a lazy quantifier *?:

    ~\[soundcloud]http://soundcloud.com/(.*?)/\[/soundcloud]~is

    You can try this too:

    ~\[soundcloud]http://soundcloud.com/([^/]+)/\[/soundcloud]~i

  3. Your capture is in the first capturing group. Then his reference is $1 not $0 that is the whole match.

  4. For your replacement string use simple quote to avoid to escape all the double quotes inside:

    '<iframe width="100%" height="166" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=$1"></iframe>'

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top