Home > Backend Development > PHP Tutorial > 字符匹配的问题

字符匹配的问题

WBOY
Release: 2016-06-23 14:16:29
Original
744 people have browsed it

请问怎么在一堆源码中匹配以下字符
img id="main-image" src="http://ecx.images-mazon.com/images/I/41Auzc7RBPL._SY300_.jpg"

我主要是想获取到图片的地址,其中41Auzc7RBPL._SY300_(图片的文件名称是随机产生的,每次都不一样的),
请问怎么获取到http://ecx.images-mazon.com/images/I/41Auzc7RBPL._SY300_.jpg


回复讨论(解决方案)

用正则处理最方便:

$str = '请问怎么在一堆源码中匹配以下字符img id="main-image" src="http://ecx.images-mazon.com/images/I/41Auzc7RBPL._SY300_.jpg"';$p = '#img\s*id="main-image"\s*src="(http://ecx\.images-mazon\.com/images/I/.+\.(jpg|gif|jpeg|png))"#U';preg_match($p, $str, $result) && var_dump($result);
Copy after login

根据情况也可以解析为DOM:
$html = '<div><img  id="main-image" src="http://ecx.images-mazon.com/images/I/41Auzc7RBPL._SY300_.jpg" / alt="字符匹配的问题" ></div>';$doc = new DOMDocument();$doc->loadHTML($html);echo $doc->getElementById('main-image')->getAttribute('src');
Copy after login


经循环100000次测试,后者的速度是前者正则的7倍,而且随着测试源字符串的体积增大,差距将可能更大

41Auzc7RBPL._SY300_这个字符串是随机产生的,每次都不样,后面那个DOM直接用了这个字符串了,而文件名是不知道的

$str='img id="main-image" src="http://ecx.images-mazon.com/images/I/41Auzc7RBPL._SY300_.jpg"';$p = |img id="main-image" src="(.*)"|iUs;preg_match($p, $str, $result);print_r($result);//如果你只需要对获取到的网址里那个图片名称那么你需要分割$ep=explode('/',$result[0]);echo $ep[5];
Copy after login

学习一下,我就会正则来处理,二楼果断高手

preg_match正则取就好了~实在不会字符串分割都可以的吧

学习一下 PHP解析DOM 之前没注意到这个方法  

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template