问题
The problem: using a hardcoded string, this works. However, using my dynamic content from $post_content, the regex returns an empty array. What I expect it to return is my expected output, where it gets all results from capture group 1 in an array from this this regex function.
I have the following function:
$post_content = (string)strstr($post_content, 'MyNeedle', true);
If I print_r() the result of this function:
"Je naam (verplicht) [text* your-test] Je e-mailadres (verplicht) [email* your-tester] Onderwerp [text your-testerer] Je bericht [textarea your-testererer] [submit \"Verzenden\"] 1 Postcode [text* postalCode] Adres [email* streetAddress] Onderwerp [text your-subject] Je bericht [textarea your-message] [submit \"Verzenden\"] 1";
If I var_dump() the result of this function:
string(278) " Je naam (verplicht) [text* your-test] Je e-mailadres (verplicht) [email* your-tester] Onderwerp [text your-testerer] Je bericht [textarea your-testererer] [submit "Verzenden"] 1 " string(258) " Postcode [text* postalCode] Adres [email* streetAddress] Onderwerp [text your-subject] Je bericht [textarea your-message] [submit "Verzenden"] 1 "
I have the following regex function:
preg_match_all($re, $post_content, $fields);
Expected output:
array(3) {
[0]=>
string "Je naam (verplicht)"
[1]=>
string "Je e-mailadres (verplicht)"
[2]=>
string "Onderwerp"
}
etc.
My output:
array(1) {
[0]=>
string(0) ""
}
array(1) {
[0]=>
string(0) ""
}
Full example code:
// DOESNT WORK
$post_content = (string)strstr($post_content, 'MyNeedle', true);
// WORKS
$post_content = "Je naam (verplicht) [text* your-test] Je e-mailadres (verplicht) [email* your-tester] Onderwerp [text your-testerer] Je bericht [textarea your-testererer] [submit \"Verzenden\"] 1 Postcode [text* postalCode] Adres [email* streetAddress] Onderwerp [text your-subject] Je bericht [textarea your-message] [submit \"Verzenden\"] 1";
// REST OF THE FUNC
$re = '/([^][\s]+(?:\h+[^][\s]+)*)?\h+\[(?:\w+\*?\h+)?([^][]+)]/';
preg_match_all($re, $post_content, $fields);
$uniqueKeys = array_unique($fields[1]);
var_dump($uniqueKeys);
Why does capture group 1 not return the expected value when I use the strstr function?
来源:https://stackoverflow.com/questions/62431649/regex-expression-on-strstr-function-returns-empty-capture-group