Solved

php preg_replace not working

Posted on 2010-11-23
4
345 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
Learn how to create flexible layouts using relative units in CSS.  New relative units added in CSS3 include vw(viewports width), vh(viewports height), vmin(minimum of viewports height and width), and vmax (maximum of viewports height and width).

724 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