I am trying to extract a string from another string using php.
At the moment im using:
<?php
$testVal = $node->field_link[0]['view'];
$testVal = preg_replace("#((http|https|ftp)://(\S*?\.\S*?))(\s|\;|\)|\]|\[|\{|\}|,|\"|'|:|\<|$|\.\s)#ie", "'<a href=\"$1\" target=\"_blank\">$3</a>$4'", $testVal);
print "testVal = ";
print $testVal;
?>
This seems to be printing my entire string at the moment.
Now what i want to do is: extract a web address if there is one and save it as a variable called testVal.
I am a novice so please explain what i am doing wrong. Also i have looked at other questions and have used the regex from one.
For @bos
Input:
<iframe width="560" height="315" src="http://www.youtube.com/embed/CLXt3yh2g0s" frameborder="0" allowfullscreen></iframe>
Desired Output
http://www.youtube.com/embed/CLXt3yh2g0s
Well, you say you want to populate
$testValwith the extracted web address, but you’re usingpreg_replaceinstead ofpreg_match. You usepreg_replacewhen you wish to replace occurrences, and you usepreg_match(orpreg_match_all) when you want to find occurrences.If you want to replace URLs with links (
<a>tags) like in your example, use something like this:If you want to instead simply locate a URL from a string, try (using your regex now instead of mine above):
When you use
preg_match, the (optional) third parameter is filled with the results of the search.$matches[0]would contain the string that matched the entire pattern,$matches[1]would contain the first capture group,$matches[2]the second, and so on.