Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove characters before and including a specific symbol

Tags:

string

php

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

like image 371
Gregory Schultz Avatar asked Oct 13 '15 08:10

Gregory Schultz


2 Answers

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.

like image 166
rdiz Avatar answered Oct 12 '22 23:10

rdiz


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);
like image 25
Vishnu R Nair Avatar answered Oct 12 '22 22:10

Vishnu R Nair