Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

php preg_replace not working

Posted on 2010-11-23
4
Medium Priority
?
353 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 2000 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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Find out what you should include to make the best professional email signature for your organization.
Originally, this post was published on Monitis Blog, you can check it here . In business circles, we sometimes hear that today is the “age of the customer.” And so it is. Thanks to the enormous advances over the past few years in consumer techno…
In this tutorial viewers will learn how to embed Flash content in a webpage using HTML5. Ensure your DOCTYPE declaration is set to HTML5: "<!DOCTYPE html>": Use the <object> tag to embed Flash content.: To specify that the object is Flash content, d…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
Suggested Courses

564 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