skip to Main Content

I have this code:

<?php $wptitle = get_the_title( get_the_ID() ); $wptitle = str_replace(" – word1 word2", "", $wptitle); echo $wptitle; ?>

But it does now work. When I put only one sting it works perfectly. I’m working in WordPress

2

Answers


  1. Chosen as BEST ANSWER

    It almost works, but it does not replace hyphen "-"

    <?php $wptitle = get_the_title( get_the_ID() ); $wptitle = str_replace(array("Word1", "Word2", "-"), "", $wptitle); echo $wptitle; ?>
    

    What I mean is Word1 and Word2 is replaced but third sting which is "-" is not replaced and I dont know why...


  2. Opening php tag declares that the following code should be interpreted as PHP by the server (rather than just HTML and being passed onto the client)

     <?php
    

    The following line declares a variable with the identifier (name) $wptitle and sets its value equal to the result of calling the function get_the_title with the argument get_the_ID. these functions must be declared elsewhere.

    $wptitle = get_the_title( get_the_ID() );
    

    The next one reassigns the variable $wptitle to be the same string with the string "foo" being replaced by the string "bar"

     $wptitle = str_replace("foo", "bar", $wptitle);
    

    If you want to replace some more strings then you can repeat this line

    $wptitle = str_replace("baz", "blink", $wptitle);
    

    In such case all occurrences of the string "foo" and "bar" will be replaced.

    Alternatively you can pass arrays to str_replace to perform multiple replacements in one go.

    $wptitle = str_replace(array("foo", "bar", "baz"), "", $wptitle);
    

    The next line prints out the contents of the variable $wptitle

     echo $wptitle; 
    

    Finally this line instructs the PHP interpreter that the PHP block is over

    ?>
    

    For more information on the semantics of str_replace have a look at the php manual page

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search