0

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?

markratledge
  • 17,322
  • 12
  • 60
  • 106
  • Can you give example strings and expected results associated please ? I don't get the space and colon point. – OlivierH Nov 29 '13 at 15:18

3 Answers3

2

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);
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
  • As one that struggles with REGEX from time to time (dont have to use them that often) Thank you for breaking it out and adding the comments! This is truly how you each :-) – buzzsawddog Nov 29 '13 at 15:20
  • 1
    Thanks! That works great. Now I should to learn more about regex as a result of your explanation of each aspect of the solution. – markratledge Nov 29 '13 at 15:54
1

You can do this:

$mytitle = ltrim(explode(':', $mytitle, 2)[1]);
Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125
0

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

bagonyi
  • 3,258
  • 2
  • 22
  • 20