2015-12-26 125 views
1

获得第一图像时,我有串:意外导致字符串

<img style="max-width:100%" src="http://media.doisongphapluat.com/thumb_x670x/2015/12/26/thumon.png" alt=""> 

试图让这个形象的src:

<?php 
preg_match('/<img.+src=[\'"](?P<src>.+)[\'"].*>/i', $step6[0], $image); 
echo $image['src']; ?> 

结果:

http://media.doisongphapluat.com/thumb_x670x/2015/12/26/thumon.png" alt=" 

为什么“ alt =“”出现在这里以及如何删除它?

回答

0

你可以在src=使用explode();然后剪掉剩余="在每一端,如果你不想让他们:

<?php 
$string = '<img style="max-width:100%" src="http://media.doisongphapluat.com/thumb_x670x/2015/12/26/thumon.png" alt="">'; 

$string = explode("src=", $string); 
$string = explode(" ", $string[1]); 
$string = substr($string[0], 1, -1); // remove 1st and last " 
echo $string; 
?> 

你需要确保你的HTML没有单一引号和逃避他们,如果它确实是这样\'

最后一行删除@SeanBright的答案在这里借用了第一和最后一个字符:Delete first character and last character from String PHP

$string = explode('src=', $string);作品 - 测试。然后您只需要用$string = substr($string[0], 1, -1); // remove 1st and last "删除" "

你也可以用

$string = str_replace('"','',$string); 

删除双引号的,我认为你的正则表达式是失败的,因为它是在src =后只是让一切”,但在空间不停止,其他人在别处评论这正则表达式是不是分手了HTML的最可靠方法。

如果你不希望explode();你可以使用strpos()substr();

$string = '<img style="max-width:100%" src="http://media.doisongphapluat.com/thumb_x670x/2015/12/26/thumon.png" alt="">'; 

$pos = strpos($string,'http'); 
$string = substr($string,$pos, -9); // remove last " and alt-... 
echo $string; 
分割字符串如果图像标签到底是因为你,所以你需要使用多一点的代码使完全程序化的

这只会工作,但会失败,如果关闭/>标签在那里:

$string = '<img style="max-width:100%" src="http://media.doisongphapluat.com/thumb_x670x/2015/12/26/thumon.png" alt="">'; 

$pos = strpos($string,'http'); // find position of !http! 
$string = substr($string,$pos); /// get string after !http" 
$len = strlen($string);   // get the length of resulting string 
$pos1 = strpos($string,'"');  // find last " 
$difpos = $len - $pos1;   // get the difference to use for the minus 
$string = substr($string,0,-$difpos); // get the string from 0 to "minus" position at end. 
echo $string; 
0

尝试:

<?php 
$input = "<img style='max-width:100%' src='http://media.doisongphapluat.com/thumb_x670x/2015/12/26/thumon.png' alt='' />"; 
$pattern = "/(http.+)'\salt/"; 
preg_match($pattern, $input, $matches); 
echo $matches[1]; 
?> 

它会给:

http://media.doisongphapluat.com/thumb_x670x/2015/12/26/thumon.png

$matches[1]给出括号内的内容,\s用于alt之前的空格。

1

问题是src组中的.+重复是贪婪的。因此,它会尽量匹配尽可能多的字符,从而超出了属性的范围。

要解决它,你可以简单地重复懒通过在末尾添加一个问号 - .+?

More on the subject


所以只要改变你的正则表达式:

<img.+src=[\'"](?P<src>.+?)[\'"].*> 

See it in action