使用正则表达式检索字符串中特殊字符之间的链接

时间:2016-02-11 15:11:26

标签: php regex

我想检索(Ampersand)lt;之间的链接;和(&符号)gt;从下面的字符串。

<http://www.test.com>

然后我想用链接替换上面的字符串。该字符串位于文件中,因此我使用以下代码替换文件中的字符串:

$contents = file_get_contents($path);
$contents = str_replace($id."\n", "", $contents);
if($count>0){
  file_put_contents($filename,$contents);
}

但是我无法弄清楚我需要做的正则表达式,有人可以帮忙吗?我可以使用此选择整个字符串,但不能选择我需要的链接。

"\&[l][t]\;(.*?)\&[g][t]\;"

2 个答案:

答案 0 :(得分:2)

您可以使用trimhtmlspecialchars_decode

在没有任何正则表达式的情况下执行此操作
$s = '<http://www.test.com>';
$s = trim(htmlspecialchars_decode($s), "<>");
echo $s; // => http://www.test.com

请参阅IDEONE demo

htmlspecialchars_decode会将特殊HTML实体转换回字符,而trim会从字符串的开头和结尾删除<>

答案 1 :(得分:0)

由于Wiktors的建议,这是我的解决方案。希望它可以帮助其他人!

function removeUnwantedSignsFromContact($path){
    $contents = file_get_contents($path);
    if(preg_match( '/\&[l][t]\;(.*?)\&[g][t]\;/', $contents, $match )){
      $filteredContact = trim(htmlspecialchars_decode($match[0]), "<>");
      $contents = str_replace($match[0], $filteredContact, $contents);
      file_put_contents($path,$contents);
      return simplexml_load_file($path);
    }
}