$split_point = \' - \';
$string = \'this is my - string - and more\';
How can i make a split using the second instance of $split_point and not the
You may use strrev to reverse the string, and then reverse the results back:
$split_point = ' - ';
$string = 'this is my - string - and more';
$result = array_map('strrev', explode($split_point, strrev($string)));
Not sure if this is the best solution though.
Just an idea:
function explode_reversed($delim,$s){
$result = array();
$w = "";
$l = 0;
for ($i = strlen($s)-1; $i>=0; $i-- ):
if ( $s[$i] == "$delim" ):
$l++;
$w = "";
else:
$w = $s[$i].$w;
endif;
$result[$l] = $w;
endfor;
return $result;
}
$arr = explode_reversed(" ","Hello! My name is John.");
print_r($arr);
Result:
Array
(
[0] => John.
[1] => is
[2] => name
[3] => My
[4] => Hello!
)
But this is much slower then explode. A test made:
$start_time = microtime(true);
for ($i=0; $i<1000;$i++)
$arr = explode_reversed(" ","Hello! My name is John.");
$time_elapsed_secs = microtime(true) - $start_time;
echo "time: $time_elapsed_secs s<br>";
Takes 0.0625 - 0.078125s
But
for ($i=0; $i<1000;$i++)
$arr = explode(" ","Hello! My name is John.");
Takes just 0.015625s
The fastest solution seems to be:
array_reverse(explode($your_delimiter, $your_string));
In a loop of 1000 times this is the best time I can get 0.03125s.
$split_point = ' - ';
$string = 'this is my - string - and more';
$result = end(explode($split_point, $string));
This is working fine
Assuming you only want the first occurrence of $split_point to be ignored, this should work for you:
# retrieve first $split_point position
$first = strpos($string, $split_point);
# retrieve second $split_point positon
$second = strpos($string, $split_point, $first+strlen($split_point));
# extract from the second $split_point onwards (with $split_point)
$substr = substr($string, $second);
# explode $substr, first element should be empty
$array = explode($split_point, $substr);
# set first element as beginning of string to the second $split_point
$array[0] = substr_replace($string, '', strpos($string, $substr));
This will allow you to split on every occurrence of $split_point after (and including) the second occurrence of $split_point.
Here is another way of doing it:
$split_point = ' - ';
$string = 'this is my - string - and more';
$stringpos = strrpos($string, $split_point, -1);
$finalstr = substr($string,0,$stringpos);
If I understand correctly, you want the example case to give you ('this is my - string', 'and more')?
Built-in split/explode seems to be forwards-only - you'll probably have to implement it yourself with strrpos. (right-left search)
$idx = strrpos($string, $split_point);
$parts = array(substr($string, 0, $idx), substr($string, $idx+strlen($split_point)))