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

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

问题描述:

i am doing some DOM parsing, and i have some strings i have to clean, they look like this:

$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()"

etc etc, you can see the system, i only need the last URL in the string, the amount of strings is variable, and the amount of links inside the strings is aswell, but i only need the last link in each string.

Should i use REGEX or a series of explode ?

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

  $ str1 =“var arrayImg = new Array(); arrayImg [0] = 
http://somepage.com/2013-5-11/1/1.jpg \  n; 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 \ N; arrayImg [0] = 
http://somepage.com/2013-5-11/1/3.jpg \ N; getImgString()“
 代码 >  pre> 
 
 

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

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

With 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

Most of people stuck in situation whether they have to use regex or any other predefined functions. You have to use predefined functions if your task can be accomplished with them otherwise use regex if none of them available to accomplish your task.

If the string contain consistent pattern, use explode(), it's panlessly easier and you don't have to worry about risk of regex-logic. Use regex otherwise.

if you want exactly regex (not exploding the string) try this:

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

UPD found an error, code updated