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
https://forums.phpfreaks.com/topic/235884-replace-first-occurrence/
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..

 

 

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.