Jump to content

preg_match and preg_replace


AHA7

Recommended Posts

     

Hello,

 

I want to search a string for a .com URL which may contain a trailing slash. If it does contain a trailing slash I want to strip it out using preg_replace. If it doesn't contain a trailing slash then I want to keep it as is and in both cases I want to store the no-trailing-slash-URL in the variable $URL_with_trailing_slash_stripped. (I do not want to affect the original string).

 

Here's my solution:

 

preg_match('/http://.*\.com[/]?/', $string, $matches);
$URL_with_trailing_slash_stripped = preg_replace('//$/', '', $matches[0]);

 

And here are my two questions:

 

1- Is the second line of the code above valid? Does preg_replace return a string and so I can store it in a variable? If not, how can I convert it to a string and store it in a variable?

 

2- Do I have to wrap the regex with forward slashes '//$/' (I have seen people do so and I don't know why)?

 

Link to comment
Share on other sites

replace the / (delimiters).. with something else..

 

IE

preg_replace('#/$#', '', $matches[0]);

 

can you give some example of what you have and want

 

ie

 

/test//data//123/

to

/test/data/123/

 

but

//test//data//123//

stays as is

//test//data//123//

 

thats just an example..

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.