Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP remove characters after last occurrence of a character in a string

Tags:

substring

php

So the test case string may be:

http://example.com/?u=ben 

Or

http://example.com 

I'm trying to remove everything after the last occurrence of a '/' but only if it's not part of the 'http://'. Is this possible!?

I have this so far:

$url = substr($url, 0, strpos( $url, '/')); 

But does not work, strips off everything after first '/'.

like image 820
benhowdle89 Avatar asked May 24 '12 23:05

benhowdle89


People also ask

How do I trim a string after a specific character in PHP?

The substr() and strpos() function is used to remove portion of string after certain character.

How can I remove last 3 characters from a string in PHP?

To remove the last three characters from a string, we can use the substr() function by passing the start and length as arguments.

How do you remove portion of a string before a certain character in PHP?

You can use strstr to do this. Show activity on this post. The explode is in fact a better answer, as the question was about removing the text before the string.


2 Answers

You must use strrpos function not strpos ;-)

substr($url, 0, strrpos( $url, '/')); 
like image 120
user2422121 Avatar answered Oct 16 '22 23:10

user2422121


You should use the tool that is designed for this type of job, parse_url

url.php

<?php  $urls = array('http://example.com/foo?u=ben',                 'http://example.com/foo/bar/?u=ben',                 'http://example.com/foo/bar/baz?u=ben',                 'https://foo.example.com/foo/bar/baz?u=ben',             );   function clean_url($url) {     $parts = parse_url($url);     return $parts['scheme'] . '://' . $parts['host'] . $parts['path']; }  foreach ($urls as $url) {     echo clean_url($url) . "\n"; } 

Example:

·> php url.php                                                                                                  http://example.com/foo http://example.com/foo/bar/ http://example.com/foo/bar/baz https://foo.example.com/foo/bar/baz 
like image 22
sberry Avatar answered Oct 17 '22 00:10

sberry