1

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

<?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 );
4

2 回答 2

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);

将输出

大批
(
    [0] => 一些带有转义 \' 引号的字符串
    [1] => 另一个非空的 \' 引号
)
于 2012-08-26T16:17:08.157 回答
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 模式以将其隔开一点,使其更易于阅读。

于 2012-08-26T23:55:03.553 回答