Reputation: 8726
How can I remove the texts in a sentence after the second comma
but do nothing if it has no two commas
in a sentence?
I tried the following:
substr($str, 0, strpos($str, ',', strpos($str, ',')+1))
But the problem here is if I don't have two commas in this $str
, the funtion outputs nothing, I'm getting a blank area.
Is there anyway to check the existence of two commas and remove text after the second comma or do nothing otherwise.
Upvotes: 0
Views: 843
Reputation: 48073
Assuming that you want to remove the second comma and all subsequent characters (because of your selected answer), using regex is very concise and direct and can be written without any pre-checking and conditions.
Match the first the first occurring comma, match one or more non-comma characters, then forget those characters with \K
, then explicitly match the second comma and all remaining characters -- to be replaced with an empty string.
Code: (Demo)
$str = "a,b,c,d";
var_export(
preg_replace("/,[^,]+\K,.*/", '', $str)
);
Upvotes: 0
Reputation: 761
A more elegant approach, without using string functions and reusing the array as we need it to count the number of commas anyway (and avoiding regex madness for readability):
$text_segments = explode(',', $str);
if( count($text_segments) > 2 ) {
$str = $text_segments[0] . ',' . $text_segments[1];
}
Upvotes: 1
Reputation: 3093
Just check the # of occurrences first:
if (substr_count($str, ',') >= 2)
substr($str, 0, strpos($str, ',', strpos($str, ',')+1));
Or you could do it with preg_match()
but it would be slower:
if (preg_match('/([^,]*,){2}/', $str, $match))
$str = $match[1];
Or in a single step (ala adeneo above, but altered to fit the instructions)
$str = preg_replace('/((?:[^,]*,){2})?(?:.*)$/', '$1', $str);
You'll notice the initial characters with comma at the end are made optional by the question-mark at the end of (...)?
so it will get the correct value regardless.
Upvotes: 0
Reputation: 21789
Try this:
$commasCount = count(explode(',', $str));
if ($commasCount > 2) {
$str = substr($str, 0, strpos($str, ',', strpos($str, ',')+1));
}
Upvotes: 2