从正则表达式匹配结果中删除字符串(如果链接包含特定属性,则删除链接类)

时间:2013-11-09 07:13:43

标签: php regex str-replace preg-replace-callback

我正在尝试使用我的PHP代码从包含属性data-class =“false”的链接中删除class =“something”,并保留其他链接。

$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;

下面的所需结果:(请注意,如果data-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

2 个答案:

答案 0 :(得分:0)

这应该有效

$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);

答案 1 :(得分:0)

从您显示的代码中我看不出使用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留出子模式,我们将摆脱空间。