Solved

php preg_replace not working

Posted on 2010-11-23
4
336 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

This article describes how to create custom column layout styles for Bootstrap. The article uses 5 columns to illustrate the concept, but the principle can be extended to any number of columns.
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
In this tutorial viewers will learn how to style elements, such a divs, with a "drop shadow" effect using the CSS box-shadow property Start with a normal styled element, such as a div.: In the element's style, type the box shadow property: "box-shad…
In this tutorial viewers will learn how to code links for mobile sites that, once clicked, send a call or text to a specified number. For a telephone link (once clicked, calls a number), begin with a normal "<a href=" link tag. For the href, specify…

763 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

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now