A
A
AlodYk2020-02-21 23:33:41
PHP
AlodYk, 2020-02-21 23:33:41

When working with preg_replace, the element that I want to pull out of the line does not come out, what could be the problem?

I am writing my router for custom routing on the site. There was such a problem:
When running the following script, I do not get data from the string after applying the regular expression in preg_replace:

$pattern_regex = preg_replace("/\{(.*?)\}/", "(?P<$1>[\w-]+)", $pattern);
$pattern_regex = "#^" . $pattern_regex . "$#";
var_dump($pattern_regex);


The data that goes into the $pattern variable :
/home
/user
/user/profile/{id}
/user/{id}/edit


Should be:
string(9) "#^/home$#"
string(9) "#^/user$#"
string(32) "#^/user/profile/(?P<id>[\W-]+)$#"
string(29) "#^/user/(?P<id>[\W-]+)/edit$#"


The following comes out:
string(9) "#^/home$#"
string(9) "#^/user$#"
string(32) "#^/user/profile/(?P[\W-]+)$#"
string(29) "#^/user/(?P[\W-]+)/edit$#"


I thought I was messing around somewhere, I found an online sandbox on the Internet for using preg_replace, everything works like clockwork there, but for me, because of the insertion of characters on the sides: "<" and ">", the element that should fit when exiting the line disappears, so even the characters themselves do not even come out. If I remove them or leave spaces between them and the string variable $1, then everything is fine, which is the essence of this joke.
I'm watching a video of one of the PHP Skills participants, it seems like he doesn't have such jokes with these regular expressions.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
dodo512, 2020-02-21
@AlodYk

echo "<xmp>";
var_dump($pattern_regex);
echo "</xmp>";

N
nokimaro, 2020-02-22
@nokimaro

Everything looks fine, the code is working and outputs what is expected
https://3v4l.org/X3JQA
I think the problem is that you see the results of the code in the browser, and they <id>are processed as an html tag and therefore they are not visible.
In order to verify this, you can open the source code of the page (Ctrl + U) and see if there <id>really is

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question