Jump to content

How would I str_replace this?


Jeffro

Recommended Posts

I want to basically delete any word that ends with ...

 

So.. If I have the following phrase:  Elvis Pres...

 

I want to remove the word Pres... entirely. 

 

Basically, something along the lines of...  $myphrase = str_replace("Pres...",'',$myphrase);

except that I never know what $myphrase will be, so the above won't work. 

 

Is it str_replace I need or something else? 

Link to comment
https://forums.phpfreaks.com/topic/236870-how-would-i-str_replace-this/
Share on other sites

Add the hyphen to the list of allowed characters (between the brackets). Since the hyphen has special meaning inside the square brackets, it will have to be escaped or added at the beginning or end:

 

$new_string = preg_replace('/ [a-zA-Z-]+\.\.\./', '', $string);

 

Now, to answer your next question (before you ask it): what about "words" with numbers in them?

 

Add the numbers, or we can change the original suggestion to just catch everything except a space ...

 

$new_string = preg_replace('/ [a-zA-Z0-9-]+\.\.\./', '', $string); // A-Z (upper or lowercase), numbers and hyphen
$new_string = preg_replace('/ [^ ]+\.\.\./', '', $string); // Anything that is not a space. 

 

In every case, since we are using the "+" qualifier, you will not be getting rid of ellipses that immediately follow a space. If you change the "+" to an "*", you should cover that case as well.

 

Note: This is NOT anchored at the end of the string, if there is something... in the middle of the string, it will go away, too. To anchor it at the end of the string add a "$" to the end of the regexp:

 

$new_string = preg_replace('/ [^ ]+\.\.\.$/', '', $string);

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.