Re: preg_replace() 'space' the final frontier
| From: | Mike Frazer | Date: | Thu, 31 Jan 2002 00:40:15 +0000 |
| Subject: | Re: preg_replace() 'space' the final frontier | ||
| References: | 1 2 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-82827@lists.php.net to get a copy of this message | ||
NOTE: That was done very quickly and only works on single character
searches! I'm working on one that will find multi-character strings. Gimme
a few mins and email me off-list if you want it.
Mike
"Mike Frazer" <mike@invertedmind.com> wrote in message
news:20020130213414.28318.qmail@pb1.pair.com...
> 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" <hdanaher@earthlink.net> wrote in message
> 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
>
>
>
>