Count spaces within exploded quotations
In simplest terms im trying t开发者_高级运维o change the data string if more than 4 spaces are found within quotations. I'm able to do this on a simple string but not within exploded quotes as it becomes an array which count functions wont accept. Is there a regex to do what im looking for in this case or something?
$data = 'Hello World "This is a test string! Jack and Jill went up the hill."';
$halt = 'String had more than 4 spaces.';
$arr = explode('"', $data);
if (substr_count($arr, ' ') >= 4) {
$data = implode('"', $arr);
$data = $halt;
As far as I understand your request, this will do the job
$data = 'Hello World "This is a test string! Jack and Jill went up the hill."';
$halt = 'String had more than 4 spaces.';
// split $data on " and captures them
$arr = preg_split('/(")/', $data, -1, PREG_SPLIT_DELIM_CAPTURE);
// must we count spaces ?
$countspace = 0;
foreach ($arr as $str) {
// swap $countspace when " is encountered
if ($str == '"') $countspace = !$countspace;
// we have to count spaces
if ($countspace) {
// more than 4 spaces
if (substr_count($str, ' ') >= 4) {
// change data
$data = $halt;
break;
}
}
}
echo $data,"\n";
output:
String had more than 4 spaces.
If you define:
function count_spaces($str) {return substr_count($str, ' '); }
you can then use array_sum(array_map("count_spaces", $arr))
to count all of the spaces in all of the strings in $arr
.
精彩评论