Why does preg_replace_callback never fire in this function?
-
16-10-2019 - |
Question
In the function below, the save_content function runs, but the doReplace does not (echo
"This is the doReplace" never shows. Any ideas why?
add_action('content_save_pre', 'save_content');
function save_content($content){
global $post;
$mykeyword = rseo_getKeyword($post);
$mykeyword = preg_quote($mykeyword, '/');
$content = preg_replace_callback("/\b($mykeyword)\b/i","doReplace", $content);
return $content;
}
function doReplace($matches)
{
echo "This is the doReplace";
die;
}
Solution
Your function needs to return the data, not echo it..
function doReplace($matches) {
return "This is the doReplace";
}
Hope that helps..
OTHER TIPS
Shouldn't the preg_quote() call be used in an array map call? If you're feeding it something like "foo|bar" it'll get escaped as "foo\|bar", which won't match anything... Better use something like this:
// uncomment in case you're returning a string:
// $kw = explode('|', $kw);
// create a new function if php 5.3 is not an option
$regex = array_map(function($in) {
return preg_quote($in, '/');
}, $kw);
$regex = implode('|', $regex);
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange