|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
[2021-09-29 07:22 UTC] requinix@php.net
-Summary: named capture group key missing if not found
+Summary: named capture group key missing if not found if not
using PREG_UNMATCHED_AS_NULL
-Status: Open
+Status: Not a bug
-Package: *General Issues
+Package: PCRE related
[2021-09-29 07:22 UTC] requinix@php.net
[2021-09-29 09:05 UTC] hkirsman at gmail dot com
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Fri Oct 24 20:00:01 2025 UTC |
Description: ------------ My PHP version is actually 7.4.23. My issue is that I have regex named capture group (to catch language from URL) and sometimes the key is not there if nothing is found. It was working fine at some point as it was returning keys with empty strings. At some point keys were not there anymore. All I could think of is that I had made small changes to my regex. Is this a bug or working ok? I've added more comments in the script. Test script: --------------- <?php $path = '/elearning'; # Does not add empty lang to $matches. $regex_path_lang_match_not_found = '#/(?P<lang>[^/]+/)?elearning#'; # Adds empty lang to $matches. $regex_path_empty_lang_match_found = '#(?P<lang>)/elearning$#'; $regex_match = preg_match($regex_path_lang_match_not_found . 'u', $path, $matches); // Doc says If PREG_UNMATCHED_AS_NULL flag is passed, unmatched subpatterns are // reported as null; otherwise they are reported as an empty string. echo 'lang key is gone but should it?'; print_r($matches); $regex_match = preg_match($regex_path_lang_match_not_found . 'u', $path, $matches, PREG_UNMATCHED_AS_NULL); echo 'PREG_UNMATCHED_AS_NULL adds it back'; print_r($matches); $regex_match = preg_match($regex_path_empty_lang_match_found . 'u', $path, $matches); echo 'Similar regex, lang is not matched, but key exists'; print_r($matches); Expected result: ---------------- lang key is gone but should it?Array ( [0] => /elearning [lang] => [1] => ) PREG_UNMATCHED_AS_NULL adds it backArray ( [0] => /elearning [lang] => [1] => ) Similar regex, lang is not matched, but key existsArray ( [0] => /elearning [lang] => [1] => ) Actual result: -------------- lang key is gone but should it?Array ( [0] => /elearning ) PREG_UNMATCHED_AS_NULL adds it backArray ( [0] => /elearning [lang] => [1] => ) Similar regex, lang is not matched, but key existsArray ( [0] => /elearning [lang] => [1] => )