Excellent, thanks a lot Chris.
Steve
(jalist)
[EMAIL PROTECTED]
http://ls2k.org
-----Original Message-----
From: Chris Hayes [mailto:[EMAIL PROTECTED]]
Sent: 18 January 2001 15:43
To: jalist; PHP
Subject: Re: [PHP] (Newbie) String within a string
jalist:
> I'm trying to grab a string from within a string based on a matching word
or
> phrase. Example...
You say you want the middle, not two words before and two words after.
I see several ways.
1. Explode into an word-array and use that:
1. prepare string
a) add spaces after comma's and fullstops by some replace
operation (replace ',' by ', ').
b) remove double spaces
2. split to an array using explode (space as string separator)
Now you have every word in a separate place in the array
3. Get # of words by count($array)
4. Divide by two and get nearest integer (hence floor and +0.5!)
$mid= floor(count($array)/2 + 0.5)
OH NO, correction, that's the middle, you wanted a specific word.
I'm afraid you'll have to walk thorugh the array to find the word
you need.
for (i=0;i<count($array);i++)
{
if ($array[$i]==$searchword)
{ $fragment= "...".
$array[$mid-2] ." "
$array[$mid-1] ." "
$array[$mid] ." "
$array[$mid+1] ." "
$array[$mid+2] ."...";
##extra job for you: make sure $i >= 2
##
and $i <= count-2
## or you'll get an error
[exit the for loop somehow, maybe drop
this in a function and RETURN;]
}
}
OR
2. Continue with the strpos and strrpos, organize it a bit better.
For instance find the middle of the string. Split at nearest
space in leftstring and rightstring.
Make a function chop_last_word, chop last two or three words from
leftstring and add to resultstring in right order.
Same for rightstring.
I think the array way is cleaner.
Chris
--------------------------------------------------------------------
-- C.Hayes Droevendaal 35 6708 PB Wageningen the Netherlands --
--------------------------------------------------------------------
--
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]
--
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]