0

如果这个问题显得太廉价,请原谅我。

我有这条线:

preg_match_all($pattern, $_GET['id'], $arr);

当您在搜索期间传递带有空格的值时,一旦遇到空格,该值就会中断。

例如:

36 2543541284

请注意 6 和 2 之间的空格。在与此类似的情况下,仅显示 36。

空格后的数字提示将被忽略。这是给用户“找不到数据”的消息。

我尝试使用 urlencode 添加 20% 但没有运气。

preg_match_all($pattern, rawurlencode($_GET[id]), $arr);

我也尝试过 urlencode 但无济于事。

我可能做错了什么?

function format($matches)
{
    return $matches[1][0].(strlen($matches[2][0])>0?$matches[2][0]:" ").$matches[3][0].(strlen($matches[4][0])>0?"  ".$matches[4][0]:"");
}

// CONSTRUCT A REGULAR EXPRESSION
$pattern
= '/'         // regex delimiter
. '('         // START of a capture group
. '\d{2}'     // exactly two digits
. ')'         // END of capture group
. '('         // START SECOND capture group
. '[ND]?'     // letters "D" OR "N" in any order or number - This is optional
. ')'         // END SECOND capture group
. '('         // START THIRD capture group
. '\d*'       // any number of digits
. ')'         // END THIRD capture group
. '('         // START FOURTH capture group
. 'GG'        // the letters "GG" EXACTLY
. '[\d]*'     // any number of digits
. ')'         // END THIRD capture group
. '?'         // make the LAST capture group OPTIONAL
. '/'         // regex delimiter
;


 preg_match_all($pattern, rawurlencode($_GET[id]), $arr);

// REFORMAT the array
$str = format($arr);

// show what we did to the data
echo '<pre>' . PHP_EOL;
echo '1...5...10...15...20...' . PHP_EOL;
echo $pattern;
echo PHP_EOL;
//Are we getting what we asked for? This is a test. We will comment out all 6 lines if we are happy with output of our REFORMATTING.
echo $str;
echo PHP_EOL;
4

2 回答 2

0

您的正则表达式不会匹配后跟空格和其他数字的两位数字。
如果您愿意,您可以更改[ND]?[\sND]?,但如果字符串不是全数字,这也将允许空格。

如果您想要关于正则表达式的进一步建议,您需要准确地指定规则。

于 2013-01-28T18:05:49.033 回答
0

在这种情况下,正则表达式是多余的。

来自urlencode 手册

返回一个字符串,其中所有非字母数字字符-_. 均已替换为百分号 ( %) 符号,后跟两个十六进制数字和编码为加号 ( +) 符号的空格。它的编码方式与 WWW 表单中发布的数据的编码方式相同,即与 application/x-www-form-urlencoded 媒体类型中的方式相同。这与» RFC 3986编码(参见rawurlencode())的不同之处在于,由于历史原因,空格被编码为加号 ( +)

它明确指出,如果您希望将空格编码为%20,而不是+,您应该使用rawurlencode().

代码示例:

$strings = array(
    '36 2543541284',
    '1234 5678',
    'this is a string'
);
$strings_encoded = array();

foreach($strings as $string)
{
    $strings_encoded[] = rawurlencode($string);
}

var_dump($strings_encoded);

输出:

array(3) {
  [0]=>
  string(15) "36%202543541284"
  [1]=>
  string(11) "1234%205678"
  [2]=>
  string(22) "this%20is%20a%20string"
}
于 2013-01-28T18:48:45.093 回答