php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #78191 /^[a-z]+$/ can be match "\n"
Submitted: 2019-06-21 01:28 UTC Modified: 2019-06-21 02:01 UTC
From: sunweiqiang8 at gmail dot com Assigned:
Status: Not a bug Package: *Regular Expressions
PHP Version: 7.2.19 OS: CentOS 7.6
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If this is not your bug, you can add a comment by following this link.
If this is your bug, but you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: sunweiqiang8 at gmail dot com
New email:
PHP Version: OS:

 

 [2019-06-21 01:28 UTC] sunweiqiang8 at gmail dot com
Description:
------------
Only PHP can succeed.

# php
preg_match("/^[a-z]+$/", "abc\n");
#int(1)

 # javascript
var reg = /^[a-z]+$/;
console.log(reg.test("abc\n"));
# false

# java(jdk11)
System.out.println(Pattern.matches("^[a-z]+$", "abc\n"));
# false

Test script:
---------------
<?php
var_dump(preg_match("/^[a-z]+$/", "abc\n"));


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2019-06-21 02:01 UTC] danack@php.net
-Status: Open +Status: Not a bug
 [2019-06-21 02:01 UTC] danack@php.net
This is the same behaviour as Perl, and comes from the PCRE library used by PHP.

https://www.regular-expressions.info/anchors.html
"Because Perl returns a string with a newline at the end when reading a line from a file, Perl's regex engine matches $ at the position before the line break at the end of the string even when multi-line mode is turned off. Perl also matches $ at the very end of the string, regardless of whether that character is a line break. So ^\d+$ matches 123 whether the subject string is 123 or 123\n."


If you don't want this, you can use the D modifier.

https://www.php.net/manual/en/reference.pcre.pattern.modifiers.php

"D (PCRE_DOLLAR_ENDONLY)
If this modifier is set, a dollar metacharacter in the pattern matches only at the end of the subject string. Without this modifier, a dollar also matches immediately before the final character if it is a newline (but not before any other newlines). This modifier is ignored if m modifier is set. There is no equivalent to this modifier in Perl."
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Fri Apr 26 11:01:31 2024 UTC