Question

I have a text string generated by get_the_title(); (a WordPress function) that has a colon : in the middle of text.

I.e., what I want to strip in the title : what I want to keep in the title

I need to strip out the text to the left of the colon, as well as the colon itself and the single space that is to the right of the colon.

I'm using this to grab the title and strip the text to the left of the colon,

$mytitle = get_the_title();
$mytitle = strstr($mytitle,':'); 
echo $mytitle;

but I'm also trying to use this to then strip the colon and the space to the right of it

substr($mytitle(''), 2);

like this:

$mytitle = get_the_title(); 
$mytitle = strstr($mytitle,':'); 
substr($mytitle(''), 2);
echo $mytitle;

but I get a php error.

Is there a the way to combine the strstr and the substr?

Or is there another way - maybe with a regular expression (which I don't know) - to strip everything to the left of the colon, including the colon and the single space to the right of it?

Était-ce utile?

La solution

A regex would be perfect:

$mytitle = preg_replace(
    '/^    # Start of string
    [^:]*  # Any number of characters except colon
    :      # colon
    [ ]    # space/x', 
    '', $mytitle);

or, as a one-liner:

$mytitle = preg_replace('/^[^:]*: /', '', $mytitle);

Autres conseils

You can do this:

$mytitle = ltrim(explode(':', $mytitle, 2)[1]);

$title = preg_replace("/^.+:\s/", "", "This can be stripped: But this is needed");

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top