Jason Paddle Jason Paddle - 1 month ago 8
PHP Question

Remove url and leave only last part of it

I know is something pretty simple for someone who understand well preg_replace but I can't understand how to remove part of url. I have form where user should enter a

token
. The problem is that some users submitted whole url with
token
this kind of url

https://example.com/page/token

and

http://example.com/page/token


I want when user submit the form to check if he/she inserted whole url and if is to remove everything and leave only
token
there

I've tried simple preg_replace like this

$result = preg_replace('https://example.com/page/', '', $str);


But error says


Warning: preg_replace(): Delimiter must not be alphanumeric or backslash


Then I've tried to escape those backslashes with
\
etc .. but same error occurred.

Any help is appreciated.

Answer

Your preg_replace() function should be like this:

$result = preg_replace('$(https|http)://example.com/page/$', '', $str);

You can use $ as a delimiter.

Comments