BentCoder
BentCoder

Reputation: 12750

Get dynamic replacement with preg_replace()

This is my url:

ftp://dynamic_text:[email protected]/so-on/param

My regex will turn it into this:

ftp://*****:*****@my-ftp-domain.com/so-on/param

Note that the url can start with either ftp or http.

regex:

My regex below will always return ftp regardless if my url started with http.

preg_replace('@(ftp|http)://(.*:.*)\@@', 'ftp://****:****@', $url);

Now my question is: how can I modify my code, so that it will dynamically return ftp or http depending on how my url started.

I read about Named Groups, but I wasn't able to solve it.

Upvotes: 1

Views: 95

Answers (1)

Rizier123
Rizier123

Reputation: 59701

Just change the ftp part in your replacement to $1 to get the value of the first group, e.g.

preg_replace('@(ftp|http)://(.*:.*)\@@', '$1://****:****@', $url);
                                        //^^

Upvotes: 4

Related Questions