正则表达式不适用于空字符串

时间:2012-08-26 15:37:23

标签: php regex

我想在单个字符串之间获取内容,但是,如果内容为空,我的正则表达式失败...

<?PHP
$string = "
blaat = 'Some string with an escaped \' quote'; // some comment.
empty1 = ''; // omg! an empty string!
empty2 = ''; // omg! an empty string!
";

preg_match_all( '/(?<not>\'.*?[^\\\]\')/ims', $string, $match );

echo '<pre>';
print_r( $match['not'] );
echo '</pre>';
?>

这将作为输出:

Array
(
    [0] => 'Some string with an escaped \' quote'
    [1] => ''; // omg! an empty string!
empty2 = '
)

我知道这个问题可以通过以下正则表达式修复,我想我正在寻找一个真正的解决方案,而不是修复每个例外......

preg_match_all( '/((\'\')|(?<not>\'(.*?[^\\\])?\'))/ims', $string, $match );

2 个答案:

答案 0 :(得分:1)

<?php
$string = "
blaat = 'Some string with an escaped \' quote'; // some comment.
empty1 = ''; // omg! an empty string!
empty2 = ''; // omg! an empty string!
not_empty = 'Another non empty with \' quote'; 

";

$parts = preg_split("/[^']*'(.*)'.*|[^']+/", $string, 0, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

print_r($parts);

将输出

Array
(
    [0] => Some string with an escaped \' quote
    [1] => Another non empty with \' quote
)

答案 1 :(得分:0)

<?PHP
$string = "
blaat = 'Some string with an escaped \' quote'; // some comment.
empty1 = ''; // omg! an empty string!
empty2 = ''; // omg! an empty string!
";

preg_match_all( '/(?<not>
    \'          #match first quote mark
    .*?         #match all characters, ungreedy
    (?<!\\\)    #use a negative lookbehind assertion
    \'
    )
/ixms', $string, $match );

echo '<pre>';
print_r( $match['not'] );
echo '</pre>';

?>

为我工作。我还添加了/ x freespacing模式以将其分开并使其更易于阅读。