Php Preg_Match 获取数组中带引号的字符串
Php Preg_Match to get Quoted string in array
需要获取数组中带引号的字符串和不带引号的字符串
示例数据
$string='tennissrchkey1 tennissrchkey2 "tennis srch key 3" "tennis srch key 4" "tennis srch key 5"';
期望的输出
Array
(
[0] => tennissrchkey1
[1] => tennissrchkey2
[2] => tennis srch key 3
[3] => tennis srch key 4
[4] => tennis srch key 5
)
到目前为止尝试过这个但还没有成功
if (preg_match('/"([^"]+)"/', $string, $m)) {
echo '<pre>';
print_r($m);
} else {
//preg_match returns the number of matches found,
//so if here didn't match pattern
}
非常感谢任何帮助!!!
谢谢!!!
<?php
$sString = 'tennissrchkey1 tennissrchkey2 "tennis srch key 3" "tennis srch key 4" "tennis srch key 5"';
$aTmp = explode( ' "', $sString );
$iCountPieces = count( $aTmp );
for( $i = 0; $i < $iCountPieces; ++$i )
{
$aFormatted[] = trim( $aTmp[ $i ], '"' );
}
var_dump( $aFormatted );
?>
使用preg_match_all
函数进行全局匹配。 (?|....)
调用了 branch reset group。分支重置组内的备选方案共享相同的捕获组。
$re = '~(?|"([^"]*)"|(\S+))~m';
$str = 'tennissrchkey1 tennissrchkey2 "tennis srch key 3" "tennis srch key 4" "tennis srch key 5"';
preg_match_all($re, $str, $matches);
print_r($matches[1]);
输出:
Array
(
[0] => tennissrchkey1
[1] => tennissrchkey2
[2] => tennis srch key 3
[3] => tennis srch key 4
[4] => tennis srch key 5
)
需要获取数组中带引号的字符串和不带引号的字符串
示例数据
$string='tennissrchkey1 tennissrchkey2 "tennis srch key 3" "tennis srch key 4" "tennis srch key 5"';
期望的输出
Array
(
[0] => tennissrchkey1
[1] => tennissrchkey2
[2] => tennis srch key 3
[3] => tennis srch key 4
[4] => tennis srch key 5
)
到目前为止尝试过这个但还没有成功
if (preg_match('/"([^"]+)"/', $string, $m)) {
echo '<pre>';
print_r($m);
} else {
//preg_match returns the number of matches found,
//so if here didn't match pattern
}
非常感谢任何帮助!!!
谢谢!!!
<?php
$sString = 'tennissrchkey1 tennissrchkey2 "tennis srch key 3" "tennis srch key 4" "tennis srch key 5"';
$aTmp = explode( ' "', $sString );
$iCountPieces = count( $aTmp );
for( $i = 0; $i < $iCountPieces; ++$i )
{
$aFormatted[] = trim( $aTmp[ $i ], '"' );
}
var_dump( $aFormatted );
?>
使用preg_match_all
函数进行全局匹配。 (?|....)
调用了 branch reset group。分支重置组内的备选方案共享相同的捕获组。
$re = '~(?|"([^"]*)"|(\S+))~m';
$str = 'tennissrchkey1 tennissrchkey2 "tennis srch key 3" "tennis srch key 4" "tennis srch key 5"';
preg_match_all($re, $str, $matches);
print_r($matches[1]);
输出:
Array
(
[0] => tennissrchkey1
[1] => tennissrchkey2
[2] => tennis srch key 3
[3] => tennis srch key 4
[4] => tennis srch key 5
)