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
Share on other sites

Thanks to all for the replies.

 

In using Abra's code, it seems to do the trick except for one exception... words that have a hyphen in them.  How can I expand to the code to work as it is but also for hyphenated words?

 

Thanks. 

Link to comment
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);

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.