Page 1 of 1

Loop not looping all the way through

Posted: Tue Sep 05, 2006 7:14 am
by impulse()
feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


The following code searches for a specified string, within a specified string. It's not useful for anything besides my learning. I hoping it's possible to output the string you're searching in and make the searched for string bold. For example if I searched for "c" within string "a b c d e f g" I would want it to output: found [b]c[/b] inside of a b [b]c[/b] d e f g. This is the code I have but it only outputs the string it's found. I have the following code which runs without errors.

Note: I am a beginner at PHP and I know I have rough edged coding in there.

Code: Select all

$searchString = $_REQUEST["searchingFor"];
$inputString = $_REQUEST["inWhat"];
$explode = $searchString;

if (ereg("$searchString", $inputString)) {
  echo "The data you searched for (<b>$searchString</b>) was found";
  }
  $exploded = explode(" ", $explode);
  for ($i = 0; $i < strlen($searchString) + 1; $i++) {
    if ($exploded[$i] == $searchString) {
      echo "<b> $exploded[$i]";
    }
    else if ($exploded[$i] != $searchString) {
    echo "$exploded[$i]";
    $i++;
  }
}


if (!(ereg("$searchString", $inputString))) {
  echo "The data you searched for (<b>$searchString</b>) was not found.";
  }

feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]

Posted: Tue Sep 05, 2006 7:33 am
by feyd
Tip: use preg_match and the other pcre functions instead of ereg, they're often faster and will be the only regex natively available moving forward.

If I was building this myself, I would likely use preg_quote() and preg_replace()/preg_replace_callback(). Your code seems overcomplicated.

On an administrative side: We've had to change or add tags in your posts for five of the twelve posts you've made thus far. Please start using the correct tags.