FRIHOST FORUMS SEARCH FAQ TOS BLOGS COMPETITIONS
You are invited to Log in or Register a free Frihost Account!


How to do this find and replace





bukaida
I want to find the sequence -(- in a string and want to replace it by <br>-(- or \n-(- which ever is suitable. The part of the code I am using for it is

Code:

-----some code above----

foreach ( $res2 as $entry )
      {
         
         $pattern='/[-(-]/';
         $replacement='/[<br>-(-]/';
         
         $entry = preg_replace($pattern,$replacement,$entry);
         
         print "$entry\n";
         
      }

-----some code below----



and the output I am getting is something like this

---------------------------------------

OUTPUT

-(-]//[
-(-]//[

which is obviously not the desired output. Should I use regular expression (not quite familiar)? Please help.
jmraker
I don't see a need for using the preg_replace function, you can use the str_replace function

Code:
foreach ( $res2 as $entry ){
    $entry = str_replace('-(-', '<br>-(-', $entry);
    print "$entry\n";
}
Fire Boar
jmraker is correct. If you were to use preg_replace, then you need to learn a bit about regular expressions:

[] is a character class: [...] will match one character from everything inside the brackets.
() is a group: (...) will match everything inside the parentheses, with the | character used to mean OR.

So /[-(-]/ is actually an invalid regular expression, but PHP does its best, in this case for some reason it matches everything. So each character is replaced with /[<br>-(-]/, <br> is being rendered as a newline in the web page.

The correct expression is:

Code:
preg_replace('/\-\(\-/', '<br>-(-', $entry);


or, as jmraker correctly pointed out, more efficient is simply:

Code:
str_replace('-(-', '<br>-(-', $entry);
bukaida
Thanx to both of you. The problem is now solved following your suggestion.
Flakky
I find preg_replace hard to use so if possible use str_replace because it is much easier Smile
Nemesis234
Flakky wrote:
I find preg_replace hard to use so if possible use str_replace because it is much easier Smile

well considering they both do much the same thing, you would only need to use preg if you was doing more complex search and replace operation.
Related topics
NotePad Replacements
Search function
PHP - Find and Delete
e-books vs. hardcopy
htaccess
What soft to replace a complete Windows by a complete Linux?
SQL UPDATING TABLE
God is not what you think It is.
Find in all html files
Save as .html or .php
Got a new domain
Renaming Multiple Files At Once (Windows)
Php free editor
How do I minimize windows
Reply to topic    Frihost Forum Index -> Scripting -> Php and MySQL

FRIHOST HOME | FAQ | TOS | ABOUT US | CONTACT US | SITE MAP
© 2005-2011 Frihost, forums powered by phpBB.