Strip text from from the left of a character, and that character and a space, too

StackOverflow https://stackoverflow.com/questions/20288780

  •  06-08-2022
  •  | 
  •  

Вопрос

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