A
A
Anastasia2021-07-02 02:06:20
PHP
Anastasia, 2021-07-02 02:06:20

Why regex101 and php return different result?

Hello. I have a string and I need to get everything that is after the first \n (this is not a line break, but a slash and a beech n). I do it like this
https://regex101.com/r/zZoGvw/1
but when I translate it into php, for some reason I get only the phone, and then no.

$z = "Запрос на доступ\nТелефон: 79991457764\nДанные: Останкин Ostoonekeen";
preg_match("/(?<=\\n).*/", $z, $user_info);
p($user_info);
/*Array
(
    [0] => Телефон: 79991457764
)*/


Question
1. What am I doing wrong?
2. How do I get from my line Phone: 79991457764\nData: Ostankin Ostoonekeen ?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Anastasia, 2021-07-02
@nastya97core

explode("\n", $z, 2)[1]
or regular expression: but it is slower
preg_match("/(?<=\n).*/s", $z, $user_info);

G
galaxy, 2021-07-02
@galaxy

Because at you both lines different, and expressions.
In PHP, the string parser handles the backslash:

$z = "Запрос на доступ\nТелефон: 79991457764\nДанные: Останкин Ostoonekeen";
$r = "/(?<=\\n).*/";
var_dump($z);
var_dump($r);

/*
string(101) "Запрос на доступ
Телефон: 79991457764
Данные: Останкин Ostoonekeen"
string(11) "/(?<=\n).*/"
*/

There is no such processing on regex01 and \n is just a slash and the letter n.
Use single quotes for such strings (or double the number of slashes).

M
mletov, 2021-07-02
@mletov

Just break the string at \n, and then join the resulting array back into a string, only without the first (null) element
https://stackoverflow.com/questions/1483497/how-ca...
https://www.php.net /manual/en/function.implode.php

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question