2016-02-11 32 views
2

我想检索(&)之间的链接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

你可以做到这一点,而无需使用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

感谢这正是我所需要的工作! – olliejjc16

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); 
    } 
} 
相关问题