我试图让我的PHP代码从包含属性数据的链接中删除class=“某样东西”-class=“false”,而不使用其他链接。
$mytext = 'text text text <a href="/url" data-class="false" class="something">
link1</a> text text text <a href="/url" class="something">link2</a> text text
text <a href="/url" class="something" data-class="false">link3</a> text text
text';
// This function is supposed to remove the class="something" string from matches.
function remove_class($matches) {
return str_replace(' class="something"','', $matches[1]);
}
// Match any link that contains the data-class="false" string and do callback.
$mytext = preg_replace_callback('/<a.*?data-class="false".*?>/',
'remove_class', $mytext);
echo $mytext;希望得到的结果如下:(注意,在数据- class =“false”存在的地方,类被移除)
text text text <a href="/url" data-class="false">link1</a> text text text
<a href="/url" class="something">link2</a> text text text
<a href="/url" data-class="false">link3</a> text text text发布于 2013-11-09 07:28:58
从您正在向我展示的代码中,我看不到使用preg_replace_callback的理由,preg_replace应该足够了。
$mytext = 'text text text <a href="/url" data-class="false" class="something">
link1</a> text text text <a href="/url" class="something">link2</a> text text
text <a href="/url" class="something" data-class="false">link3</a> text text
text';
// Match any link that contains the data-class="false" and class="something"
// Then removes class="something".
$mytext = preg_replace('/(<a.*?)(class="something")\s(.*?data-class="false".*?>)|(<a.*?)(data-class="false".*?)\s(class="something")(.*?>)/',
'$1$3$4$5$7', $mytext);
echo $mytext;将产出:
text text text <a href="/url" data-class="false">
link1</a> text text text <a href="/url" class="something">link2</a> text text
text <a href="/url" data-class="false">link3</a> text text
text所发生的是preg_replace与class="something" data-class="false"或data-class="false" class="something"匹配。每个子模式(.)可以由子模式的$和编号引用。如果我们发现了前三个子模式,那么我们使用$1$3,省略$2,将匹配替换为我们想要的子模式匹配。由于子模式$4-$7,我们没有使用,它们被忽略,反之亦然,如果我们匹配$4-$7。如果把\s排除在子模式之外,我们将摆脱和额外的空间。
发布于 2013-11-09 07:23:38
这应该能行
$mytext = 'text text text <a href="/url" data-class="false" class="something">
link1</a> text text text <a href="/url" class="something">link2</a> text text
text <a href="/url" class="something" data-class="false">link3</a> text text
text';
$mytext2= str_replace('data-class="false" class="something"','data-class="false"', $mytext );
$mytext3= str_replace('class="something" data-class="false"','data-class="false"', $mytext2 );
echo htmlentities($mytext3);https://stackoverflow.com/questions/19873437
复制相似问题