Reputation: 1804
I would like to get the content in between of a single string, however, if the content is empty, my regex is failing...
<?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>';
?>
This will give as output:
Array
(
[0] => 'Some string with an escaped \' quote'
[1] => ''; // omg! an empty string!
empty2 = '
)
I know this problem can be fixed with the following regex, thought i'm looking for a true solution in stead of a fix for every exception...
preg_match_all( '/((\'\')|(?<not>\'(.*?[^\\\])?\'))/ims', $string, $match );
Upvotes: 1
Views: 155
Reputation: 3495
<?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);
will output
Array ( [0] => Some string with an escaped \' quote [1] => Another non empty with \' quote )
Upvotes: 1
Reputation: 1124
<?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>';
?>
Worked for me. I also added the /x freespacing mode to space it out a bit and make it easier to read.
Upvotes: 0