Hi Ed,

first example has been covered by others, so onto the next:

> Pulling a word between two other words without having to know what the
word
> is.  For example, pulling whatever word displays between "the" and
> "sky".  If the string was "the blue sky", the result would be the word
> blue.  If the string were "the green sky", the result would be the word
green.

I don't quite understand what you mean by "pulling", but this example will:
1. Take out any words if they exist.
2. Store those removed words into an array for you to use later, should you
need to see what was taken out.

<?

$string = "Thse sun is often up when you look up in the blue sky. However,
the green sky often yields rain.";
echo "<b>Example 2</b><br>\n<i>Original string:</i> " . $string . "<br>\n";
if (preg_match_all("!the\s(.*?)\ssky!is", $string, $output))
{
 // Use an array to store all the matches.
 $saved = array();

 for($i=0; $i<count($output[0]); $i++)
 {
  // Push the value of the match into an array.
  array_push($saved, $output[1][$i]);

  // Replace that same value from the string.
  $string = str_replace($output[1][$i], "", $string);
 }
}
else
{
 $saved = "There were no matches found in the pattern.";
}

echo "<i>Replaced:</i> " . $string . "<br>\n<br>\n";

if (!is_array($saved))
{
 echo $saved;
}
else
{
 echo "The following words were taken out of the pattern:<br>\n";
 for ($i=0; $i<count($saved); $i++)
 {
  echo $saved[$i] . "<br>\n";
 }
}

?>

There's nothing complicated about the match:
preg_match_all() - see manual
! delimiters !
the - first word
\s - space
(.*?) - everything up to next (non greedy)
\s - space
sky - word
i - case insensitive
s -  treat new lines (\n as .)

If you just want to rip stuff out, then you can use preg_replace():

$string = preg_replace("!(the)\s.*?(\ssky)!is", "$1$3", $string);

See the manual, or search these archives for further examples if you're
struggling.... Regexes (and when to use them) take a little getting used to,
 but they're definitely worth learning :)

Hope it helps.

James



-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to