计算爆炸报价中的空格

时间:2011-05-10 02:05:30

标签: 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('"', $data);
if (substr_count($arr, ' ') >= 4) {
$data = implode('"', $arr);
$data = $halt;

2 个答案:

答案 0 :(得分:1)

如果你定义:

function count_spaces($str) {return substr_count($str, ' '); }

然后,您可以使用array_sum(array_map("count_spaces", $arr))来计算$arr中所有字符串中的所有空格。

答案 1 :(得分:1)

据我了解您的要求,这将完成工作

$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.