过滤这些字符串PHP的最佳方法

时间:2013-07-08 01:21:44

标签: php regex

我正在做一些DOM解析,我有一些字符串我必须清理,它们看起来像这样:

$str1 = "var arrayImg=new Array();arrayImg[0]=
http://somepage.com/2013-5-11/1/1.jpg
;getImgString()";


$str2 = "var arrayImg=new Array();arrayImg[0]=
http://somepage.com/2013-5-11/1/1.jpg
;arrayImg[0]=
http://somepage.com/big/qingliang/2013-5-11/1/2.jpg
;getImgString()"


$str3 = "var arrayImg=new Array();arrayImg[0]=
http://somepage.com/2013-5-11/1/1.jpg
;arrayImg[0]=
http://somepage.com/2013-5-11/1/2.jpg
;arrayImg[0]=
http://somepage.com/2013-5-11/1/3.jpg
;getImgString()"

等等,你可以看到系统,我只需要字符串中的最后一个URL,字符串的数量是可变的,字符串内的链接数量也是如此,但我只需要每个字符串中的最后一个链接

我应该使用REGEX还是一系列爆炸?

3 个答案:

答案 0 :(得分:1)

使用explode

$arr = explode(';',$str);
$arr = $arr[count($arr) - 2]; // get the last link
$arr = trim($arr,"arrayImg[0]="); //here you will get only the last link

Live Demo

大多数人都不得不使用正则表达式或任何其他预定义函数。如果您的任务可以使用它们完成任务,则必须使用预定义函数,否则使用正则表达式(如果它们都不可用于完成任务)。

答案 1 :(得分:1)

如果字符串包含一致的模式use explode(),它就会变得更加容易,您不必担心正则表达式逻辑的风险。否则请使用regex

答案 2 :(得分:0)

如果你想要正确的正则表达式(不爆炸字符串),试试这个:

preg_match_all ("/http\S+/", $str, $matches);
$link = $matches[0][count($matches[0])-1];

UPD发现错误,代码已更新

相关问题