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);
Related
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
I have a string that looks a little like this, world:region:bash
It divides folder names, so i can create a path for FTP functions.
However, i need at some points to be able to remove the last part of the string, so, for example
I have this world:region:bash
I need to get this world:region
The script wont be able to know what the folder names are, so some how it needs to be able to remove the string after the last colon.
$res=substr($input,0,strrpos($input,':'));
I should probably highlight that strrpos not strpos finds last occurrence of a substring in given string
$tokens = explode(':', $string); // split string on :
array_pop($tokens); // get rid of last element
$newString = implode(':', $tokens); // wrap back
You may want to try something like this:
<?php
$variable = "world:region:bash";
$colpos = strrpos($variable, ":");
$result = substr($variable, 0, $colpos);
echo $result;
?>
Or... if you create a function using this information, you get this:
<?php
function StrRemoveLastPart($string, $delimiter)
{
$lastdelpos = strrpos($string, $delimiter);
$result = substr($string, 0, $lastdelpos);
return $result;
}
$variable = "world:region:bash";
$result = StrRemoveLastPart($variable, ":");
?>
Explode the string, and remove the last element.
If you need the string again, use implode.
$items = array_pop(explode(':', $the_path));
$shotpath = implode(':', $items);
Use regular expression /:[^:]+$/, preg_replace
$s = "world:region:bash";
$p = "/:[^:]+$/";
$r = '';
echo preg_replace($p, $r, $s);
demo
Notice how $ which means string termination, is made use of.
<?php
$string = 'world:region:bash';
$string = implode(':', explode(':', $string, -1));
I have many strings that follow the same convention:
this.is.a.sample
this.is.another.sample.of.it
this.too
What i want to do is isolate the last part. So i want "sample", or "it", or "too".
What is the most efficient way for this to happen. Obviously there are many ways to do this, but which way is best that uses the least resources (CPU and RAM).
$string = "this.is.another.sample.of.it";
$contents = explode('.', $string);
echo end($contents); // displays 'it'
I realise this question is from 2012, but the answers here are all inefficient. There are string functions built into PHP to do this, rather than having to traverse the string and turn it into an array, and then pick the last index, which is a lot of work to do something quite simple.
The following code gets the last occurrence of a string within a string:
strrchr($string, '.'); // Last occurrence of '.' within a string
We can use this in conjunction with substr, which essentially chops a string up based on a position.
$string = 'this.is.a.sample';
$last_section = substr($string, (strrchr($string, '-') + 1));
echo $last_section; // 'sample'
Note the +1 on the strrchr result; this is because strrchr returns the index of the string within the string (starting at position 0), so the true 'position' is always 1 character on.
http://us3.php.net/strpos
$haystack = "this.is.another.sample.of.it";
$needle = "sample";
$string = substr( $haystack, strpos( $haystack, $needle ), strlen( $needle ) );
Just do:
$string = "this.is.another.sample.of.it";
$parts = explode('.', $string);
$last = array_pop(parts);
$new_string = explode(".", "this.is.sparta");
$last_part = $new_string[count($new_string)-1];
echo $last_part; // prints "sparta".
$string = "this.is.another.sample.of.it";
$result = explode('.', $string); // using explode function
print_r($result); // whole Array
Will give you
result[0]=>this;
result[1]=>is;
result[2]=>another;
result[3]=>sample;
result[4]=>of;
result[5]=>it;
Display any one you want (ex. echo result[5];)
I am looking to get the filename from the end of a filepath string, say
$text = "bob/hello/myfile.zip";
I want to be able to obtain the file name, which I guess would involve getting everything after the last slash as a substring. Can anyone help me with how to do this is PHP? A simple function like:
$fileName = getFileName($text);
Check out basename().
For more general needs, use negative value for start parameter.
For e.g.
<?php
$str = '001234567890';
echo substr($str,-10,4);
?>
will output
1234
Using a negative parameter means that it starts from the start'th character from the end.
$text = "bob/hello/myfile.zip";
$file_name = end(explode("/", $text));
echo $file_name; // myfile.zip
end() returns the last element of a given array.
As Daniel posted, for this application you want to use basename(). For more general needs, strrchr() does exactly what the title of this post asks.
http://us4.php.net/strrchr
I suppose you could use strrpos to find the last '/', then just get that substring:
$fileName = substr( $text, strrpos( $text, '/' )+1 );
Though you'd probably actually want to check to make sure that there's a "/" in there at all, first.
function getSubstringFromEnd(string $string, int $length)
{
return substr($string, strlen($string) - $length, $length);
}
function removeSubstringFromEnd(string $string, int $length)
{
return substr($string, 0, strlen($string) - $length);
}
echo getSubstringFromEnd("My long text", 4); // text
echo removeSubstringFromEnd("My long text", 4); // My long
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);
}