If you want a function to return all text in a string up to the Nth occurrence of a substring, try the below function.
Works in PHP >= 5.
(Pommef provided another sample function for this purpose below, but I believe it is incorrect.)
<?php
function nsubstr($needle, $haystack, $n_occurrence)
{
$arr = explode($needle,$haystack,$n_occurrence);
$last = count($arr) - 1;
$pos_in_last = strpos($arr[$last],$needle);
if ($pos_in_last !== false)
$arr[$last] = substr($arr[$last],0,$pos_in_last);
return implode($needle,$arr);
}
$string = 'd24jkdslgjldk2424jgklsjg24jskgldjk24';
print 'S: ' . $string . '<br>';
print '1: ' . nsubstr('24',$string,1) . '<br>';
print '2: ' . nsubstr('24',$string,2) . '<br>';
print '3: ' . nsubstr('24',$string,3) . '<br>';
print '4: ' . nsubstr('24',$string,4) . '<br>';
print '5: ' . nsubstr('24',$string,5) . '<br>';
print '6: ' . nsubstr('24',$string,6) . '<br>';
print '7: ' . nsubstr('24',$string,7) . '<br>';
?>
Note that this function can be combined with wordwrap() to accomplish a routine but fairly difficult web design goal, namely, limiting inline HTML text to a certain number of lines. wordwrap() can break your string using <br>, and then you can use this function to only return text up to the N'th <br>.
You will still have to make a conservative guess of the max number of characters per line with wordwrap(), but you can be more precise than if you were simply truncating a multiple-line string with substr().
See example:
<?php
$text = 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Pellentesque id massa. Duis sollicitudin ipsum vel diam. Aliquam pulvinar sagittis felis. Nullam hendrerit semper elit. Donec convallis mollis risus. Cras blandit mollis turpis. Vivamus facilisis, sapien at tincidunt accumsan, arcu dolor suscipit sem, tristique convallis ante ante id diam. Curabitur mollis, lacus vel gravida accumsan, enim quam condimentum est, vitae rutrum neque magna ac enim.';
$wrapped_text = wordwrap($text,100,'<br>',true);
$three_lines = nsubstr('<br>',$wrapped_text,3);
print '<br><br>' . $three_lines;
$four_lines = nsubstr('<br>',$wrapped_text,4);
print '<br><br>' . $four_lines;
?>