Forums

how do I find and replace wordpress content characters? (4 posts)

  1. dacosta_rafael
    Member
    Posted 3 months ago #

    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;

  2. dacosta_rafael
    Member
    Posted 3 months ago #

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

    ?>

  3. Harry
    Member
    Posted 3 months ago #

    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 :)

  4. rightmost
    Member
    Posted 3 weeks ago #

    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');
    ?>

Reply

You must log in to post.

About this Topic