Jump to content

Replace First Occurrence


TheMayhem

Recommended Posts

Pretty basic question here,

 

I have a string called:

 

$string

 

I want to use a php replace function or whatever would be best to find the first occurence of ] and for the string to delete from ] And everything after that first occurence of ] In the string.

 

Example

 

$string = "Hello Friends [Test] My name is John";

 

After the php function

 

$string "Hello Friends [Test";

Link to comment
Share on other sites

$string = preg_replace("@(.*)\]@", $1, "Hello Friends [Test] My name is John");

 

This won't work. First off, you need to wrap $1 in quotes in the replace argument.  2nd, this pattern will greedily match everything to the end of the string and then give up characters until it finds a ] so IOW it will actually match for the last occurrence of ] in the string.  And then the $1 will replace everything it matched before that so IOW this pattern just removes the last occurring ] in the string :P

 

preg_replace approach would be more like "~^([^\]]*).*~"  Basically you have to use a pattern that matches the entire string.  More efficient would be to use preg_match and just match the bit you actually want.  More efficient would be to use other functions like strpos, substr, explode, etc..

 

 

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.