Pierce McGeough
Pierce McGeough

Reputation: 3086

Use PHP to extract specific string data

The iframe is assigned to a variable $string. I want extract the texts between embed/ and ?rel in the iframes src. So i would be looking for this code sL-2oYAI35o

<iframe width="420" height="315" src="http://www.youtube.com/embed/sL-2oYAI35o?rel=0" frameborder="0" allowfullscreen></iframe>

Would I need to use a php substr function or regex? I cant use the regular substring because the start value may differ.

Upvotes: 0

Views: 148

Answers (2)

Valery Viktorovsky
Valery Viktorovsky

Reputation: 6726

$text = '<iframe width="420" height="315" src="http://www.youtube.com/embed/sL-2oYAI35o?rel=0" frameborder="0" allowfullscreen></iframe>';

preg_match('`embed/(.+)\?rel`i', $text, $matches);
$code = (!empty($matches[1])) ? $matches[1] : '';

Upvotes: 0

km6zla
km6zla

Reputation: 4877

I tested this and it works.

$string = preg_replace('/embed.*\?rel/', 'embed?rel', $string);

Edit thanks to @Orangepill

$string = preg_replace('/embed(.*)\?rel/', 'embed?rel', $string);

Edit 2 I tested it and it works identically with or without the capture group.

Upvotes: 1

Related Questions