DH010010 DH010010 - 3 months ago 12
PHP Question

PHP remove string from a string between two commas where the string starts with specific item

I am trying to remove a string between two commas within a larger string that starts with a specifica item.

So this is the larger string:-

#navMain ul li a,.navBreadCrumb1 .nav1 ul li,.top-specials

I have a query that selects .navBreadCrumb1 and I want to be able to remove everything from .navBreadCrumb1 to next comma so the string above would become:-

#navMain ul li a,.top-specials

The query could select multiple items (i.e it could have selected #navMain - in which case i would need it to remove #navMain ul li a,)

I am pretty usless with preg_replace() and I guess that what I would have to use that to achive this but honestly do not have a clue.

Can any one help?


There are a number of ways to do this, here is one example if you're trying to just get rid of a section of text between two commas:

$string = '#navMain ul li a,.navBreadCrumb1 .nav1 ul li,.top-specials';
$stringArray = explode(',', $string);
$stringNew = $stringArray[0].','.$stringArray[2];
echo $stringNew;

Returns #navMain ul li a,.top-specials

The only problem with this example are the assumptions which must be made:

  • an array of the string will return 3 items
  • it really is just a string and not markup
  • it really is just as easy as concatenating the parts you want after you explode the string

Now, using preg_match() you could get yet another array using a regex pattern:


The first group matches up to the first comma, the second up to the next comma and then the rest of the string. You could code it up like this, using $string from above:

$pattern = '/(.*?,)(.*?,)(.*)/';
preg_match($pattern, $string, $matches);

$matches would contain this array:

    [0] => #navMain ul li a,.navBreadCrumb1 .nav1 ul li,.top-specials
    [1] => #navMain ul li a,
    [2] => .navBreadCrumb1 .nav1 ul li,
    [3] => .top-specials

To get the result you're looking for you would end up concatenating $matches[1] . ',' . $matches[3]

The are other regex patterns you could experiment with and use, for example you using regex lookarounds like this:

$lookaround = '/(?=,)(.*?)(?=,)/';
$newString = preg_replace($lookaround, '', $string);

The pattern matches the text below because of its relationship to the first and second comma in the string:

,.navBreadCrumb1 .nav1 ul li

Now $newString (the result of the preg_replace()) we create contains exactly what you're looking for even if the regex is not particularly efficient if you're examining a lot of strings. There is no concatenation and the pattern is much less fragile than the examples I provided previously. We essentially replace the section from the first comma to the next comma with nothing, leaving the string you're looking for.