Gregory Schultz
Gregory Schultz

Reputation: 844

Remove characters before and including a specific symbol

I have a string <?php $linktitle = get_the_title();?> that stores the title of the post. The string has a title like this:

If Your Wi-Fi Is Terrible, Check Your Router – The New York Times

How can I remove everything before and including the ? I'm using: <?php echo strstr($linktitle, '&#8211;'); ?> and it outputs:

– The New York Times

Upvotes: 11

Views: 2443

Answers (2)

Vishnu R Nair
Vishnu R Nair

Reputation: 317

I hope you need output like

– The New York Times

from

If Your Wi-Fi Is Terrible, Check Your Router – The New York Times

so try to use it may help you ,

  $linktitle = "If Your Wi-Fi Is Terrible, Check Your Router – The New York Times";

  echo substr($linktitle,strrpos($linktitle,'–'));

EDIT :

If you need to remove the "–" too . use this ,

 $linktitle         = "If Your Wi-Fi Is Terrible, Check Your Router – The New York Times";
 $specCharLen   = strlen(htmlentities("–"));
 echo substr($linktitle,strrpos($linktitle,'–')+$specCharLen);

Upvotes: 3

rdiz
rdiz

Reputation: 6176

Try using preg_replace:

preg_replace("/.+?( –)/", '', $linktitle)

If you want to remove the whitespace after the - too:

preg_replace("/.+?( –)\s*/", '', $linktitle)

This uses regular expression to match a pattern defined by any character except newline 1 or more times (.+), until it meets (?) a space followed by a dash (( –)), then a whitespace (\s) 0 or more times (*). Preg_replace then replaces the matched pattern with an empty string.

Upvotes: 13

Related Questions