How to Split a String in PHP at the Nth Occurrence of a Needle

How can I split a string in PHP at the nth occurrence of a needle?

It could be:

function split2($string, $needle, $nth) {
$max = strlen($string);
$n = 0;
for ($i=0; $i<$max; $i++) {
if ($string[$i] == $needle) {
$n++;
if ($n >= $nth) {
break;
}
}
}
$arr[] = substr($string, 0, $i);
$arr[] = substr($string, $i+1, $max);

return $arr;
}

Cut string in PHP at nth-from-end occurrence of character

just use explode with your string and if pattern is always the same then get last element of the array and your work is done

$pizza  = "piece1/piece2/piece3/piece4/piece5/piece6";
$pieces = explode("/", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2

Then reverse your array get first four elements of array and combine them using "implode"
to get desired string

Split string after second space - PHP

Answering the question as asked, this will give you two strings consisting of the original divided at the second space:

$strings = preg_split ('/ /', 'Womens Team Ranking Round', 3);
$second=array_pop($strings);
$first=implode(" ", $strings);

If you want to split on one or more spaces, use / +/ for the pattern.

You could also do it with a single regex:

$string='Womens Team Ranking Round';
preg_match('/^([^ ]+ +[^ ]+) +(.*)$/', $string, $matches);

This will give you the first two words in $matches[1] and the remainder of the string in $matches[2].

Answering a more complicated question than asked: If you want to break a longer string every two words, then you can remove the last parameter from preg_split and then use array_slice in a loop to re-join the members of the array two at a time.

Answering a question not actually asked at all but possibly the reason for a question like this: Don't forget wordwrap.

How to refer to the second occurrence of a string in php?

The strpos function accepts an optional third parameter which is an offset from which the search for the target string should begin. In this case, you may pass a call to strpos which finds the first index of comma, incremented by one, to find the second comma.

$input = "Hey, I'm trying something With PHP, Is it Working?";
echo strpos($input, ",", strpos($input, ",") + 1); // prints 34

Just for completeness/fun, we could also use a regex substring based approach here, and match the substring up the second comma:

$input = "Hey, I'm trying something With PHP, Is it Working?";
preg_match("/^[^,]*,[^,]*,/", $input, $matches);
echo strlen($matches[0]) - 1; // also prints 34

Truncate string after certain number of substring occurrences in PHP?

$string = explode( "2", $string, 5 );
$string = array_slice( $string, 0, 4 );
$string = implode( "2", $string );

See it here in action: http://codepad.viper-7.com/GM795F


To add some confusion (as people are won't to do), you can turn this into a one-liner:

implode( "2", array_slice( explode( "2", $string, 5 ), 0, 4 ) );

See it here in action: http://codepad.viper-7.com/mgek8Z


For a more sane approach, drop it into a function:

function truncateByOccurence ($haystack, $needle,  $limit) {
$haystack = explode( $needle, $haystack, $limit + 1 );
$haystack = array_slice( $haystack, 0, $limit );
return implode( $needle, $haystack );
}

See it here in action: http://codepad.viper-7.com/76C9VE

find the second occurrence of a char in a string php

Try this

preg_match_all('/-/', $info,$matches, PREG_OFFSET_CAPTURE);  
echo $matches[0][1][1];

Return the portion of a string before the first occurrence of a character in PHP

You could do this:

$string = 'The quick brown fox jumped over the lazy dog';
$substring = substr($string, 0, strpos($string, ' '));

But I like this better:

list($firstWord) = explode(' ', $string);

split string only on first instance of specified character

Use capturing parentheses:

'good_luck_buddy'.split(/_(.*)/s)
['good', 'luck_buddy', ''] // ignore the third element

They are defined as

If separator contains capturing parentheses, matched results are returned in the array.

So in this case we want to split at _.* (i.e. split separator being a sub string starting with _) but also let the result contain some part of our separator (i.e. everything after _).

In this example our separator (matching _(.*)) is _luck_buddy and the captured group (within the separator) is lucky_buddy. Without the capturing parenthesis the luck_buddy (matching .*) would've not been included in the result array as it is the case with simple split that separators are not included in the result.

We use the s regex flag to make . match on newline (\n) characters as well, otherwise it would only split to the first newline.



Related Topics



Leave a reply



Submit