View Full Version : Resolved Check next word for numeric value

02-23-2010, 07:22 PM
I'm searching the $content string for certain words, and if those words are in there, my program flags it. The problem I'm having is that a couple of these words have the option of having a number behind them. I'm not trying to flag the ones with numbers after them.. Is there a way to to this? This is a rough example of what I'm trying to do...

$content = "Crazy Random Apple 43 Left Apple Truck Plane Turtle Duck";
$needles = array("Random", "Apple", "Duck");

$spaced = split(" ", $content);
foreach($needles as $pin) {
foreach($spaced as $cstring) {
if($cstring == "Apple") { $alert = '1'; } // Found a word with possible number afterwards
elseif($alert == '1') {
if(is_numeric($cstring)) { $alert = '0'; } // Not what I want, so I reset the marker
else { flag($cstring); } // Flagged, and marker reset
elseif ($cstring == $pin && $alert != '1') { flag($cstring); } // Flag regular word

My thought was to check to see if it's one with a possible number, then set an alert. The program would then go to the next word and since the alert was set, it would check to see if the next word is a number or not and respond accordingly, and then of course I'm still checking for the other word(s)..

"Apple" still gets flagged twice... It should only be flagged once.


02-23-2010, 10:31 PM
Really, the best way to do this would be a regular expression. But I like your loops, they are more logical than some bizzare string of symbols.

So, if you want to stick with the loop concept, I would use an iterator in your loop, so I can simply check the next index using the iterator, rather than carrying some alert flag on to the next iteration in the loop.

You can stick with "foreach" but a "for" loop has iterator handling built in, so I prefer it for this kind of thing.

foreach ($needle as $pin) {
for ($i = 0; $i < count($spaced); $i++) {
if ($spaced[$i] == $pin) {
if ($i < count($spaced) - 1 && !ctype_digit($spaced[$i+1]) {

02-24-2010, 03:36 AM
Thanks Fumigator!! I hadn't even considered a for loop instead of the foreach. Very much appreciated.