努力使用正则表达式函数在字符串中查找链接


Struggling to use a regex function to find a link in a string

我正在尝试使用php从另一个字符串中提取一个字符串。

目前我正在使用:

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

这似乎正在打印我的整个字符串。

现在我想做的是:提取一个网址(如果有的话),并将其保存为一个名为testVal的变量。

我是个新手,所以请解释一下我做错了什么。此外,我还研究了其他问题,并使用了其中的regex。

对于@bos

输入:

<iframe width="560" height="315" src="http://www.youtube.com/embed/CLXt3yh2g0s" frameborder="0" allowfullscreen></iframe>

期望输出

http://www.youtube.com/embed/CLXt3yh2g0s

您说要用提取的网址填充$testVal,但您使用的是preg_replace而不是preg_match。当您希望替换出现时使用preg_replace,当您希望查找发生时使用preg_match(或preg_match_all)。

如果你想用链接(<a>标签)代替URL,就像你的例子一样,使用这样的东西:

<?php
$testVal = preg_replace(
     '/((?:https?:'/'/|ftp:'/'/|irc:'/'/)[^'s<>()"]+?(?:'([^'s<>()"]*?')[^'s<>()"]*?)*)((?:'s|<|>|"|'.||']|!|'?|,|&#44;|&quot;)*(?:['s<>()"]|$))/',
     '<a target="_blank" rel="nofollow" href="$1">$1</a>$2',
     $testVal
);

如果你想简单地从字符串中定位URL,请尝试(现在使用你的正则表达式,而不是上面的我的):

<?php
$testVal = $node->field_link[0]['view'];
if(!preg_match("#((http|https|ftp)://('S*?'.'S*?))('s|';|')|']|'[|'{|'}|,|'"|'|:|'<|$|'.'s)#ie", $testVal, $matches)) {
     echo "Not found!";
else {
     echo "URL: " . $matches[1];
}

使用preg_match时,(可选)第三个参数将填充搜索结果。$matches[0]将包含与整个模式匹配的字符串,$matches[1]将包含第一个捕获组,$matches[2]将包含第二个,依此类推