WordPress.org

Support

Support » How-To and Troubleshooting » how do I find and replace wordpress content characters?

how do I find and replace wordpress content characters?

  • I have the following code but it does not seem to change the character in wordpress

    $intro_copy = get_the_content() ;

    $intro_copy = str_replace(‘&’, ”, $intro_copy);

    echo $intro_copy;

Viewing 4 replies - 1 through 4 (of 4 total)
  • this worked for me . let me know if there is a ‘better practice’

    <?php
    function replace_content($content)
    {
    $content = str_replace(“&”, “&”, $content);
    $content = str_replace(“é”, “é”, $content);
    $content = str_replace(“—”, “—”, $content);
    $content = str_replace(“‘”, “‘”, $content);
    $content = str_replace(“’”, “’”, $content);
    $content = str_replace(‘“’, ““”, $content);
    $content = str_replace(‘”’, “””, $content);
    return $content;
    }

    ?>

    You could add what you want to find and replace into an array, and it would probably be more efficient.

    <?php
    function replace_content($content)
    {
      $search  = array('&', 'é', '—', '‘', '’', '“', '”');
      $replace = array('&', 'é', '—', '‘', '’', '“', '”');
    
      $content = str_replace($search, $replace, $content);
      return $content;
    }
    
    ?>

    Link: http://php.net/manual/en/function.str-replace.php – Check out the array examples.

    Hope this works, I haven’t actually run the above code 🙂

    Thanks Harry, that worked for me.

    Just to add on to this for anyone else interested… this is what I added to my functions.php file:

    <?php
    function replace_content($content)
    {
      //add content that you wish to replace to this array
      $search  = array('&', 'é', '—', '‘', '’', '“', '”');
      //add content that will replace old content to this array
      $replace = array('&', 'é', '—', '‘', '’', '“', '”');
    
      $content = str_replace($search, $replace, $content);
      return $content;
    }
    
    add_filter('the_content', 'replace_content');
    add_filter('the_excerpt', 'replace_content');
    ?>

    This is great! The only issue I’m having is getting this to work for custom fields. I have many custom fields, so it’s not efficient to put them all in this one function. Furthermore, as new custom fields are being created, that also leaves room for error.

    Is there a way to do a “find and replace” for an entire page? Thanks!

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘how do I find and replace wordpress content characters?’ is closed to new replies.
Skip to toolbar