Remove all characters after last instance of particular character - php

How can I remove all the content in a string after the LAST occurance of a slash character / ?
For example, the string is:
http://localhost/new-123-rugby/competition.php?croncode=12345678
I want to remove all the content after the last / so that it just shows:
http://localhost/new-123-rugby/
But the content after the / could be of a variable length.
Please note, there could be any number of slashes in the URL. It needs to be able to remove content after the last slash. There could be more than shown in the example above.

you can try this
$url = "http://localhost/new-123-rugby/competition.php?croncode=12345678";
preg_match("/[^\/]+$/", $url, $matches);
$newUrl = str_replace($matches[0],'',$url);
echo $newUrl;

Solution #1, using substr() + strrpos():
$string = 'http://localhost/new-123-rugby/competition.php?croncode=12345678';
$pos = strrpos($string, '/');
if ($pos !== FALSE) {
echo(substr($string, 0, $pos + 1));
}
Function strrpos() finds the position of the last occurrence of / in the string, substr() extracts the required substring.
Drawback: if $string does not contain '/', strrpos() returns FALSE and substr() does not return what we want. Need to check the value returned by strrpos() first.
Solution #2, using explode() + implode():
$string = 'http://localhost/new-123-rugby/competition.php?croncode=12345678';
$array = explode('/', $string);
if (count($array) > 1) {
array_pop($array); // ignore the returned value, we don't need it
echo(implode('/', $array).'/'); // join the pieces back, add the last '/'
}
Alternatively, instead of array_pop($array) we can make the last component empty and there is no need to add an extra '/' at the end:
$string = 'http://localhost/new-123-rugby/competition.php?croncode=12345678';
$array = explode('/', $string);
if (count($array) > 1) {
$array[count($array) - 1] = ''; // empty the last component
echo(implode('/', $array)); // join the pieces back
}
Drawback (for both versions): if $string does not contain '/', explode() produces an array containing a single value and the rest of the code produces either '/' (the first piece of code) or an empty string (the second). Need to check the number of items in the array produced by explode().
Solution #3, using preg_replace():
$string = 'http://localhost/new-123-rugby/competition.php?croncode=12345678';
echo(preg_replace('#/[^/]*$#', '/', $string));
Drawbacks: none. It works well when both when $string contains '/' and it does not contain '/' (it does not modify $string in this case).

NOTA:
The question was edited so that the original answer (below the edit), doesn't match the requirements from OP. It wasn't marked as an edit from OP.
EDIT:
Updated my answer so it now matches the requirements of OP:
(Now it works with as many slashes as you want)
Will also work using
http://localhost/new-123-rugby////////competition.php?croncode=12345678
<?php
$url = "http://localhost/new-123-rugby/competition.php?croncode=12345678";
echo dirname($url) . "/";
?>
Output:
http://localhost/new-123-rugby/
Original answer:
This should work for you:
<?php
$string = "http://localhost/new-123-rugby/competition.php?croncode=12345678";
echo $string = substr($string, 0, strpos(strrev($string), "/")-2);
?>
Output:
http://localhost/new-123-rugby/
Demo: http://ideone.com/0R9QUG

Related

SPLIT URL in PHP

I have below URL in my code and i want to split it and get the number from it
For example from the below URL need to fetch 123456
https://review-test.com/#/c/123456/
I have tried this and it is not working
$completeURL = https://review-test.com/#/c/123456/ ;
list($url, $number) = explode('#c', preg_replace('/^.*\/+/', '', $completeURL));
Use parse_url
It's specifically made for this sort of thing.
You can do this without using regex also -
$completeURL = 'https://review-test.com/#/c/123456/' ;
list($url, $number) = explode('#c', str_replace('/', '', $completeURL));
echo $number;
If you wan to get the /c/123456/ params you will need to execute the following:
$url = 'https://review-test.com/#/c/123456/';
$url_fragment = parse_url($url, PHP_URL_FRAGMENT);
$fragments = explode('/', $url_fragment);
$fragments = array_filter(array_map('trim', $fragments));
$fragments = array_values($fragments);
The PHP_URL_FRAGMENT will return a component of the url after #
After parse_url you will end up with a string like this: '/c/123456/'
The explode('/', $url_fragment); function will return an array with empty indexes where '/' was extracted
In order to remove empty indexes array_filter($fragments); the
array_map with trim option will remove excess spaces. It does not
apply in this case but in real case scenario you better trim.
Now if you var_dump the result you can see that the array needs to
be reindexed array_values($fragments)
You should try this: basename
basename — Returns trailing name component of path
<?php
echo basename("https://review-test.com/#/c/123456/");
?>
Demo : http://codepad.org/9Ah83qaP
Subsequently you can directly take from pure regex to fetch numbers from string,
preg_match('!\d+!', "https://review-test.com/#/c/123456/", $matches);
print_r($matches);
Working demo
Simply:
$tmp = explode( '/', $completeUrl).end();
It will explode the string by '/' and take the last element
If you have no other option than regex, for your example data you could use preg_match to split your url instead of preg_replace.
An approach could be to
Capture the first part as a group (.+\/)
Then capture your number as a group (\d+)
Followed by a forward slash at the end of the line \/$/
This will take the last number from the url followed by a forward slash.
Then you could use list and skip the first item of the $matches array because that will contain the text that matched the full pattern.
$completeURL = "https://review-test.com/#/c/123456/";
preg_match('/(.+\/)(\d+)\/$/', $completeURL, $matches);
list(, $url, $number) = $matches;

how to remove the first part of a path in php?

i have a path like this:
/dude/stuff/lol/bruh.jpg
i want to echo it like this:
/stuff/lol/bruh.jpg
how to do this? and if you could please explain it. i found one good answer
Removing part of path in php but i cannot work my way around with explode and implode.
please give me the link to the duplicate answer if my question is a duplicate
You could use strpos with substr:
$string = '/dude/stuff/lol/bruh.jpg';
$string = substr($string, strpos($string, '/', 1));
The strpos to look for the position of the / after the first one, then use substr to get the string starting from that position till the end.
$path = '/dude/stuff/lol/bruh.jpg';
$path = explode('/', $path);
unset($path[1]);
$path = implode('/', $path);
Will separate the string into an array, then unset the first item (technically the second in the array, since the first element will be empty due to the string starting with /). Finally the path is imploded, and you get:
/stuff/lol/bruh.jpg
Try this :
$string = "/dude/stuff/lol/bruh.jpg";
$firstslash = strpos($string,"/",1);
$secondstring = substr($string, $firstslash+1);
echo "String : " . $string;
echo " <br> Result : " . $secondstring;
You can use a regular expression to extract resource name you need.
preg_match('/(?P<name>[^\/]+)$/', $path, $match);
Then you have to use $match as array, and you can see the name inside of it.
$match['name];

Create an Array and get Element, or part of String, in One Line - PHP

To create an array from a string and get an element you need to do this:
$string = "1/2";
$array = explode("/", $string);
$elem = $array[0];
A little trick lets you use the strstr() and provides the same result as both lines above.
$elem = strstr($string, "/", true);
The issue is..
What if you want to return after the "/" instead of before it, but without the "/" prepended
If the "/" does not exist in the array, false is returned
strstr() is not the answer. Is there another method or syntax to get the string before the "/" in one line either by doing an array operation or some string operation?
You can do it like this in php 5.4 +
$string = "1/2";
$first = explode("/", $string)[0];
Eval.in example
You can use substr():
$after = substr($string, strpos($string, '/')+1);
the +1 makes it skip past the /.

How to get everything after a certain character?

I've got a string and I'd like to get everything after a certain value. The string always starts off with a set of numbers and then an underscore. I'd like to get the rest of the string after the underscore. So for example if I have the following strings and what I'd like returned:
"123_String" -> "String"
"233718_This_is_a_string" -> "This_is_a_string"
"83_Another Example" -> "Another Example"
How can I go about doing something like this?
The strpos() finds the offset of the underscore, then substr grabs everything from that index plus 1, onwards.
$data = "123_String";
$whatIWant = substr($data, strpos($data, "_") + 1);
echo $whatIWant;
If you also want to check if the underscore character (_) exists in your string before trying to get it, you can use the following:
if (($pos = strpos($data, "_")) !== FALSE) {
$whatIWant = substr($data, $pos+1);
}
strtok is an overlooked function for this sort of thing. It is meant to be quite fast.
$s = '233718_This_is_a_string';
$firstPart = strtok( $s, '_' );
$allTheRest = strtok( '' );
Empty string like this will force the rest of the string to be returned.
NB if there was nothing at all after the '_' you would get a FALSE value for $allTheRest which, as stated in the documentation, must be tested with ===, to distinguish from other falsy values.
Here is the method by using explode:
$text = explode('_', '233718_This_is_a_string', 2)[1]; // Returns This_is_a_string
or:
$text = end((explode('_', '233718_This_is_a_string', 2)));
By specifying 2 for the limit parameter in explode(), it returns array with 2 maximum elements separated by the string delimiter. Returning 2nd element ([1]), will give the rest of string.
Here is another one-liner by using strpos (as suggested by #flu):
$needle = '233718_This_is_a_string';
$text = substr($needle, (strpos($needle, '_') ?: -1) + 1); // Returns This_is_a_string
I use strrchr(). For instance to find the extension of a file I use this function:
$string = 'filename.jpg';
$extension = strrchr( $string, '.'); //returns "jpg"
Another simple way, using strchr() or strstr():
$str = '233718_This_is_a_string';
echo ltrim(strstr($str, '_'), '_'); // This_is_a_string
In your case maybe ltrim() alone will suffice:
echo ltrim($str, '0..9_'); // This_is_a_string
But only if the right part of the string (after _) does not start with numbers, otherwise it will also be trimmed.
if anyone needs to extract the first part of the string then can try,
Query:
$s = "This_is_a_string_233718";
$text = $s."_".substr($s, 0, strrpos($s, "_"));
Output:
This_is_a_string
$string = "233718_This_is_a_string";
$withCharacter = strstr($string, '_'); // "_This_is_a_string"
echo substr($withCharacter, 1); // "This_is_a_string"
In a single statement it would be.
echo substr(strstr("233718_This_is_a_string", '_'), 1); // "This_is_a_string"
If you want to get everything after certain characters and if those characters are located at the beginning of the string, you can use an easier solution like this:
$value = substr( '123_String', strlen( '123_' ) );
echo $value; // String
Use this line to return the string after the symbol or return the original string if the character does not occur:
$newString = substr($string, (strrpos($string, '_') ?: -1) +1);

PHP substring extraction. Get the string before the first '/' or the whole string

I am trying to extract a substring. I need some help with doing it in PHP.
Here are some sample strings I am working with and the results I need:
home/cat1/subcat2 => home
test/cat2 => test
startpage => startpage
I want to get the string till the first /, but if no / is present, get the whole string.
I tried,
substr($mystring, 0, strpos($mystring, '/'))
I think it says - get the position of / and then get the substring from position 0 to that position.
I don't know how to handle the case where there is no /, without making the statement too big.
Is there a way to handle that case also without making the PHP statement too complex?
The most efficient solution is the strtok function:
strtok($mystring, '/')
NOTE: In case of more than one character to split with the results may not meet your expectations e.g. strtok("somethingtosplit", "to") returns s because it is splitting by any single character from the second argument (in this case o is used).
#friek108 thanks for pointing that out in your comment.
For example:
$mystring = 'home/cat1/subcat2/';
$first = strtok($mystring, '/');
echo $first; // home
and
$mystring = 'home';
$first = strtok($mystring, '/');
echo $first; // home
Use explode()
$arr = explode("/", $string, 2);
$first = $arr[0];
In this case, I'm using the limit parameter to explode so that php won't scan the string any more than what's needed.
$first = explode("/", $string)[0];
What about this :
substr($mystring.'/', 0, strpos($mystring, '/'))
Simply add a '/' to the end of mystring so you can be sure there is at least one ;)
Late is better than never. php has a predefined function for that. here is that good way.
strstr
if you want to get the part before match just set before_needle (3rd parameter) to true
http://php.net/manual/en/function.strstr.php
function not_strtok($string, $delimiter)
{
$buffer = strstr($string, $delimiter, true);
if (false === $buffer) {
return $string;
}
return $buffer;
}
var_dump(
not_strtok('st/art/page', '/')
);
One-line version of the accepted answer:
$out=explode("/", $mystring, 2)[0];
Should work in php 5.4+
This is probably the shortest example that came to my mind:
list($first) = explode("/", $mystring);
1) list() will automatically assign string until "/" if delimiter is found
2) if delimiter "/"is not found then the whole string will be assigned
...and if you get really obsessed with performance, you may add extra parameter to explode explode("/", $mystring, 2) which limits maximum of the returned elements.
The function strstr() in PHP 5.3 should do this job.. The third parameter however should be set to true..
But if you're not using 5.3, then the function below should work accurately:
function strbstr( $str, $char, $start=0 ){
if ( isset($str[ $start ]) && $str[$start]!=$char ){
return $str[$start].strbstr( $str, $char, $start+1 );
}
}
I haven't tested it though, but this should work just fine.. And it's pretty fast as well
You can try using a regex like this:
$s = preg_replace('|/.*$|', '', $s);
sometimes, regex are slower though, so if performance is an issue, make sure to benchmark this properly and use an other alternative with substrings if it's more suitable for you.
Using current on explode would ease the process.
$str = current(explode("/", $str, 2));
You could create a helper function to take care of that:
/**
* Return string before needle if it exists.
*
* #param string $str
* #param mixed $needle
* #return string
*/
function str_before($str, $needle)
{
$pos = strpos($str, $needle);
return ($pos !== false) ? substr($str, 0, $pos) : $str;
}
Here's a use case:
$sing = 'My name is Luka. I live on the second floor.';
echo str_before($sing, '.'); // My name is Luka
$arr = explode("/", $string, 2); $first = $arr[0];
This Way is better and more accurate than strtok
because if you wanna get the values before # for example
while the there's no string before # it will give you whats after the sign .
but explode doesnt
$string="kalion/home/public_html";
$newstring=( stristr($string,"/")==FALSE ) ? $string : substr($string,0,stripos($string,"/"));
why not use:
function getwhatiwant($s)
{
$delimiter='/';
$x=strstr($s,$delimiter,true);
return ($x?$x:$s);
}
OR:
function getwhatiwant($s)
{
$delimiter='/';
$t=explode($delimiter, $s);
return ($t[1]?$t[0]:$s);
}

Categories