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?

有帮助吗?

解决方案

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

其他提示

You can do this:

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

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top