Home > OS >  How to replace 3 strings in post title?
How to replace 3 strings in post title?

Time:03-22

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

CodePudding user response:

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

CodePudding user response:

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...

  • Related