Solved

php preg_replace not working

Posted on 2010-11-23
4
338 Views
Last Modified: 2012-05-10
This is a hard one for me and I've been doing trial-and-error for the past two hours or so.

Anyways I have a script to search for a array of letters (split from a word entered into textfield) and it searches the sentence for those arrays.

The sentence: Dan likes the color green and likes to eat apples!

Now, on this page I have two fields. One field is for ONE word and the other field is for multiple words. So, for example, I'd type in field one `Dan` and the other field I'd type `din`. OK, so here is what I get:

http://i.imgur.com/fbeoj.png

As you can see, only the `n` in `din` is underline. If I replace `din` in the textfield to `dinl`. It will then proceed to underline the `l` in `like`. Somehow my script ONLY edits the LAST of the array in the `$new_patternstwo`. How od i make so it underlines not JUST `n` but also `d` and `i`?

Thank you for reading.

Code so far:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
    	<title>Word Checker</title>
    </head>
    <body>
    <form action="rep.php" method="post">
    word: <input type="text" value="<?=@$_POST['ana']?>" name="ana" /><br />
    sentence:  <input type="text" value="<?=@$_POST['sec']?>" name="sec" />
    <br /><br /><input type="submit" value="Find Anagram!" name="submit" />
    
    </form>
    <?php
    
    if (@$_POST['submit']) {
    $stringz = "Dan likes the color green and likes to eat apples!";
    $word = $_POST['ana'];
    $secword = $_POST['sec'];
    $letter = str_split($word);
    $lettertwo = str_split($secword);
    $patterns = array();
    $patternstwo = array();
     echo "<h1>[$word] $secword</h1>";
    $i = 0;
    foreach ($letter as $i => $word) {
        array_push($patterns, "/".$letter[$i]."/");
        $i++;
    }
    
    foreach ($lettertwo as $x => $secword) {
        array_push($patternstwo, "/".$lettertwo[$x]."/");
        $x++;
    }
    
    $new_patterns = array();
    $new_patternstwo = array();
    foreach ($patterns as $p)
          if (array_key_exists($p, $new_patterns))
          $new_patterns[$p]++;
        else
          $new_patterns[$p] = 1;
    
    foreach ($patternstwo as $x)
          if (array_key_exists($x, $new_patternstwo))
          $new_patternstwo[$x]++;
        else
          $new_patternstwo[$x] = 1;
    
    
    $string = $stringz;
    
    $success = TRUE;
    $successtwo = TRUE;
    foreach ($new_patterns as $p => $limit)
    {
      $string = preg_replace($p, '<b>\\0</b>', $string, $limit, $count);
    
      $takenout = $string;
      
      if (!$count)
      {
        $success = FALSE;
        break;
      }
    }
    
    
    foreach ($new_patternstwo as $x => $limittwo)
    {
     $stringtwo = preg_replace($x, '<u>\\0</u>', $string, $limittwo, $counttwo);
      
      $finalstring = $stringtwo;
      
      if (!$counttwo)
      {
        $successtwo = FALSE;
        break;
      }
    }
    
    if ($success == TRUE && $successtwo == TRUE) {
      echo "<span style='font-size:20pt;'>$finalstring</span><br /><textarea rows='15' cols='100'>$finalstring</textarea>";
    } else {
      echo "Nope. You didn't have all the required patterns in the array.";
    }
    
    
    
    }
    ?>
    
    </body>
    </html>

Open in new window

0
Comment
Question by:UrbanTwitch
4 Comments
 
LVL 6

Expert Comment

by:ramelong
ID: 34199193
Yo are using a case sensitive mode on the regexp, try replacing lines 26 and 31 with these::
// line 26
array_push($patterns, "/".$letter[$i]."/i");

// line 31
array_push($patternstwo, "/".$lettertwo[$x]."/i");

Open in new window

0
 
LVL 13

Expert Comment

by:dsmile
ID: 34199344
I don't know that preg_replace() has that fifth param and I think the use of limit (to not use duplicated pattern) is not neccessary and way too complicated.

Try this simple approach (I just focused on how to replace the string with input seed words)
<?php
$testString = 'Dan likes the color green and likes to eat apples!';
$testWordBold = 'Dan';
$testWordUnderline = 'dinnn';
$arySplittedWordBold = array();
for ($i = 0, $len = strlen($testWordBold); $i < $len; $i++) {
	$arySplittedWordBold[$i] = '/'. $testWordBold[$i] .'/';
}

$arySplittedWWordUnderline = array();
for ($i = 0, $len = strlen($testWordUnderline); $i < $len; $i++) {
	$arySplittedWWordUnderline[$i] ='/'. $testWordUnderline[$i] .'/';
}

$arySplittedWordBold = array_unique($arySplittedWordBold);
$arySplittedWWordUnderline = array_unique($arySplittedWWordUnderline);

$replacedString = preg_replace($arySplittedWordBold, '<b>\\0</b>', $testString);
$replacedString = preg_replace($arySplittedWWordUnderline, '<u>\\0</u>', $replacedString);
echo $replacedString;

Open in new window

0
 
LVL 2

Accepted Solution

by:
benschwartz earned 500 total points
ID: 34199454
your last loop, over $new_patternstwo, doesn't seem to be updating "$string" so each time you make a replacement, it stores the original string with the most recent replacement but overwrites the previous ones.

Try updating $string as well as $finalstring:


foreach ($new_patternstwo as $x => $limittwo)
{
 $stringtwo = preg_replace($x, '<u>\\0</u>', $string, $limittwo, $counttwo);
 
  $string = $finalstring = $stringtwo;
 
  if (!$counttwo)
  {
    $successtwo = FALSE;
    break;
  }
}
0
 
LVL 5

Author Closing Comment

by:UrbanTwitch
ID: 34208441
It works but the script underlines ALREADY bolded parts which is what I do not want. ah well i'll open up a new Q~
0

Featured Post

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is intended for those who are new to PHP error handling (https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html).  It addresses one of the most common problems that plague beginning PHP develop…
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
The viewer will receive an overview of the basics of CSS showing inline styles. In the head tags set up your style tags: (CODE) Reference the nav tag and set your properties.: (CODE) Set the reference for the UL element and styles for it to ensu…
HTML5 has deprecated a few of the older ways of showing media as well as offering up a new way to create games and animations. Audio, video, and canvas are just a few of the adjustments made between XHTML and HTML5. As we learned in our last micr…

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question