Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 计算分解引号中的空格_Php_Regex_Arrays_Count - Fatal编程技术网

Php 计算分解引号中的空格

Php 计算分解引号中的空格,php,regex,arrays,count,Php,Regex,Arrays,Count,最简单的说,如果在引号中找到超过4个空格,我会尝试更改数据字符串。我可以在一个简单的字符串上完成这项工作,但不能在分解的引号内完成,因为它变成了计数函数无法接受的数组。在这种情况下,有没有一个正则表达式来做我想要做的事情 $data = 'Hello World "This is a test string! Jack and Jill went up the hill."'; $halt = 'String had more than 4 spaces.'; $arr = explode('"

最简单的说,如果在引号中找到超过4个空格,我会尝试更改数据字符串。我可以在一个简单的字符串上完成这项工作,但不能在分解的引号内完成,因为它变成了计数函数无法接受的数组。在这种情况下,有没有一个正则表达式来做我想要做的事情

$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;
如果您定义:

function count_spaces($str) {return substr_count($str, ' '); } 函数count_spaces($str){返回substr_count($str,);}
然后,您可以使用
array\u sum(array\u map(“count\u spaces”,$arr))
来计算
$arr

中所有字符串中的所有空格。据我所知,这将完成任务

$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";
输出:

String had more than 4 spaces.

substr\u count
无法应用于数组。问题不清楚。。。是否需要查看
字符包装的任何单个子字符串中是否有4个空格?在
字符包装的所有子字符串中总共有4个以上的空格?那么用
'
包装的子字符串呢?还要注意的是,在所有3种情况下,
explode()
对您没有帮助。。。它在指定的分隔符上拆分字符串,而您真正需要的是分隔符中包含的每个子字符串。除了原始问题中的
$arr
只是
上的字符串拆分,因此计数与只执行
子字符串计数($data,”)相同
。这里有比不能对数组中的元素求和更深的问题……这几乎是完美的,除了整个字符串应该被替换,而不仅仅是引号中的内容。我自己尝试过更改它,但没有得到预期的结果。