问题
so i'm trying to do the usual replacing each instance of a company name in wordpress, and i've run into an issue where on occasion (usually in the href of links) it's breaking links.
code i'm using (includes a filter for ACF custom fields)
//Replace the word lunch with a span
function replace_text_wps($text){
$replace = array(
// 'WORD TO REPLACE' => 'REPLACE WORD WITH THIS'
'lunch!' => '<span class="lunch">lunch!</span>',
'Lunch!' => '<span class="lunch">lunch!</span>',
'LUNCH!' => '<span class="lunch">lunch!</span>'
);
$text = str_replace(array_keys($replace), $replace, $text);
return $text;
}
add_filter('the_content', 'replace_text_wps');
add_filter('the_excerpt', 'replace_text_wps');
add_filter('the_title', 'replace_text_wps');
add_filter('acf_the_content', 'replace_text_wps');
Is there a way to only replace it outside of stuff like href tags? i've looked into stuff like DOM parses but i'm not sure if there's a simpler method- it doesn't seem to cause grief in any other instances so i'm not sure that pre=processing the entire HMTL and looking for the word is appropriate. I did wonder about searching for the string including a space before and after it, but i wasn't sure how to include leading / trailing spaces, and it felt a bit bodge-y? Thanks in advance! Pete
回答1:
ok, so in this instance, which is quite specific, i've found the following code works well enough. added trailing / leading spaces in the initial matching parameters, and also variants to find it directly after html tags including with a space. less elegant, but sufficient for the purpose here.
function replace_text_wps($text){
$replace = array(
// used mid-line
' lunch! ' => ' <span class="lunch">lunch!</span> ',
' Lunch! ' => ' <span class="lunch">lunch!</span> ',
' LUNCH! ' => ' <span class="lunch">lunch!</span> ',
// used at end of lines
' lunch!' => ' <span class="lunch">lunch!</span>',
' Lunch!' => ' <span class="lunch">lunch!</span>',
' LUNCH!' => ' <span class="lunch">lunch!</span>',
// used inside html tags like headers
'>lunch!' => '><span class="lunch">lunch!</span>',
'>Lunch!' => '><span class="lunch">lunch!</span>',
'>LUNCH!' => '><span class="lunch">lunch!</span>',
//used directly after html tags
'> lunch!' => '> <span class="lunch">lunch!</span>',
'> Lunch!' => '> <span class="lunch">lunch!</span>',
'> LUNCH!' => '> <span class="lunch">lunch!</span>',
//exclude alt tags on images, title attributes etc
'"lunch!' => '"lunch!',
'lunch!"' => 'lunch!"',
'"Lunch!' => '"lunch!',
'Lunch!"' => 'lunch!"'
);
$text = str_replace(array_keys($replace), $replace, $text);
return $text;
}
add_filter('the_content', 'replace_text_wps');
add_filter('the_excerpt', 'replace_text_wps');
add_filter('the_title', 'replace_text_wps');
add_filter('acf_the_content', 'replace_text_wps');
来源:https://stackoverflow.com/questions/44409808/exclude-html-attributes-in-str-replace