PHP gave us strpos() and strrpos(), which find the first and last occurrance
of something within a string.  What they forgot was rather important:
finding the "n"th occurrance.  I wrote some code you can add to your script
(or put it in a separate file and require() it) that provides just such a
function:

function strnpos($string, $search, $nth) {
 $count = 0;
 for ($i = 0; $i < strlen($string); $i++) {
  if ($string[$i] == $search) {
   $count++;
   if ($count == $nth) { return $i; }
  }
 }
 if ($count != $nth) { return FALSE; }
}

Remember, PHP was created in C, and C strings are just arrays of characters.
That functionality partially carries over to PHP (I say partially because
"sizeof($string)" will return 1, not the length of the string).  You can
access individual characters just as you would access an individual element
of an array.  That's what the above code does.

The function returns the LOCATION of the nth occurrance, it doesn't do the
replacing for you.  You can use it with substr_replace() like so:

$string = substr_replace($string, "<br>", strnpos($string, " ", 19), 1);

or in a less compact way:

$offset = strnpos($string, " ", 19);
$string = substr_replace($string, "<br>", $offset, 1);

Hope that helps.

Mike Frazer



"Hugh Danaher" <[EMAIL PROTECTED]> wrote in message
000801c1a9c5$26007460$0100007f@localhost">news:000801c1a9c5$26007460$0100007f@localhost...

What I am trying to do is have a line of text break at a "space" after
reading 19 words.  Having read the various methods of finding and replacing
one character with another, I settled on preg_replace as my best choice, but
this function doesn't accept a space in the regular expression slot.  What
can I do to get around this, or is there a better function than the one I
selected?

$statement=preg_replace(" ","<br>",$original,19);

 Warning:  Empty regular expression in /home/www/host/document.php on line
71





-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
To contact the list administrators, e-mail: [EMAIL PROTECTED]

Reply via email to