admin管理员组

文章数量:1296912

I am trying to replace the a URL of the content with php. i tried the code mentioned below but it didn't work. is there any way to achieve this with php only?

function replace_text_wps($text){
    $replace = array(
        ';>' => ';>',
  
    );
    $text = str_replace(array_keys($replace), $replace, $text);
    return $text;
}
 
add_filter('the_content', 'replace_text_wps',99);

I am trying to replace the a URL of the content with php. i tried the code mentioned below but it didn't work. is there any way to achieve this with php only?

function replace_text_wps($text){
    $replace = array(
        'https://www.facebook/something">' => 'https://www.instagram/something">',
  
    );
    $text = str_replace(array_keys($replace), $replace, $text);
    return $text;
}
 
add_filter('the_content', 'replace_text_wps',99);
Share Improve this question asked Apr 14, 2021 at 9:18 UzairUzair 12 bronze badges 7
  • Does $text = str_replace(array_keys($replace), array_values($replace), $text); work? – kero Commented Apr 14, 2021 at 9:46
  • I don't believe this is a WP problem/question, this looks like a generic PHP question about how to use str_replace with arrays, you should ask this on stackoverflow instead, and it can be simplified to just the inside of the function – Tom J Nowell Commented Apr 14, 2021 at 10:07
  • @TomJNowell sad to see you marked this question as off-topic. the PHP codes are correct. the question is all about WordPress Hook – Uzair Commented Apr 14, 2021 at 10:45
  • Have you confirmed this code works outside of a hook with predefined strings that you can test? – Tom J Nowell Commented Apr 14, 2021 at 11:12
  • Is the text you want to replace even inside content? If you error_log or var_dump the $text, does the string you search for appear in there? – kero Commented Apr 14, 2021 at 12:05
 |  Show 2 more comments

1 Answer 1

Reset to default 1

If you give a look at the documentation, of str_replace you will find your needs. https://www.php/manual/en/function.str-replace.php

There is 3 choices for you there :

function replace_text_wps($text){
    $replace = array(
        'https://www.facebook/something">' => 'https://www.instagram/something">',
    );
    $text = str_replace(array_keys($replace), array_values($replace), $text);

    // OR
    $text = str_replace(array(
        'https://www.facebook/something">'
    ), array(
        'https://www.instagram/something">'
    ), $text);
    
    // OR 
    $text = str_replace('https://www.facebook/something">', 'https://www.instagram/something">', $text);
        
    return $text;
}
 
add_filter('the_content', 'replace_text_wps',99, 1);

本文标签: phpstrreplace with thecontent is not working