我对正则表达式很陌生。
我想瞄准href=""
中引号之间的所有内容,以便我可以快速解析html并替换链接引用的内容。
我也希望能够用img
src
属性做到这一点,但如果有人能解释如何用href
做到这一点,我将能够以同样的方式做其他属性。
如果我有这样的标记:
<a href="http://my.domain/simple-product-2.html" class="product-image"><img src="http://my.domain/media/catalog/product/cache/1/small_image/75x/9df78eab33525d08d6e5fb8d27136e95/images/catalog/product/placeholder/small_image.jpg" width="75" height="75" alt="Simple Product 2" title="Simple Product 2"></a>
<div class="product-details">
<h3 class="product-name"><a href="http://my.domain/simple-product-2.html">Simple Product 2</a></h3>
<div class="price-box">
<span class="regular-price" id="product-price-2-related">
<span class="price">$42.00</span> </span>
</div>
<p><a href="http://my.domain/wishlist/index/add/product/2/form_key/PLOSE4N7mH4kcOgX/" class="link-wishlist">Add to Wishlist</a></p>
</div>
我如何使用regex来瞄准""
之间的任何值,比如href
??
编辑:期望输出作为示例:
给定这个输入
href="http://my.domain/simple-product-2.html"
检索输出:
href="http://index.html"
不要使用regex解析HTML。PHP中使用DOM解析器:
$doc = new DOMDocument();
libxml_use_internal_errors(true);
$doc->loadHTML( $html ); // loads your html
$nodelist = $doc->getElementsByTagName('a'); // get all the <a> tags
for($i=0; $i < $nodelist->length; $i++) {
$node = $nodelist->item($i);
$val = $node->attributes->getNamedItem('href')->nodeValue;
echo "href is: $valn";
}
我想把href="
中引号之间的所有内容作为目标
根据下面注释中@lcoderre的建议,使用所有格量词从索引1中获取匹配的组。
href="([^"]*+)"
这是在线演示
试试这个,使用Positive Lookbehind &超前
(?<=href=").*?(?=")
在线演示第一个正则表达式模式的示例代码:
$re = "/href=\"([^\"]*+)\"/m";
$str = ...
preg_match_all($re, $str, $matches);