Forum Moderators: coopster

Message Too Old, No Replies

preg replace not working

         

freakyjas

4:17 am on Aug 26, 2010 (gmt 0)

10+ Year Member



basically the problem is i have an array of english words and spanish words. i then need to parse a page of html to find any english words and replace them with the spanish equivalent. i was using preg_match firstly to check if the english word was a whole word i.e. not in quotes or next to another character e.g. style= but at the same time need to be able to allow for style. (period)

do you think im going about this the right way? am i making this more complicated than it has to be?

any pointers would be great

heres the code i have so far


//if the forms submitted take the 3 fields: english, spanish and content to check
if(isset($_POST['submitted'])) {
$search = explode("\n",$_POST['search']);
$replace = explode("\n",$_POST['replace']);
$content = $_POST['haystack'];
$sr = array_combine($search,$replace);

//create arrays for preg_replace
foreach ($sr as $key => $value) {
$patterns[] = $key;
$replacements[] = $value;
}

$newcontent = preg_replace($patterns,$replacements,$content);
echo $newcontent;
}


When I run this I get a Delimiter must not be alphanumeric or backslash in ../index.php on line 21 error

Line 21 is $newcontent = preg_replace($patterns,$replacements,$content);

rocknbil

4:30 am on Aug 26, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Welcome aboard freakyjas, regexps are a bit difficult to get your head around for some, but if you break it down, it starts to make sense (after a few years.) Regexps have three basic parts: delimiter, pattern, modifier. You have no delimiters.

$text = "foobared";
$pattern = "Ed"; // or, $replace
$new = preg_replace("/$pattern/i", '', $text);
echo $new; // "foobar"

/ = delimiters. Note I used double quotes for the delimiter and pattern so it interpolates the value - had I used single quotes, it wouldn't interpolate and would try to match on the literal dollar sign followed by word "pattern."
i = modifier, means "case insensitive", match Ed, ed, eD, ED

I'm not sure of the nature of your input, give us some examples.

freakyjas

4:46 am on Aug 26, 2010 (gmt 0)

10+ Year Member



just want to add that ive tried using the regex /\b.$patterns.\b\ to only find whole words but without a lot of joy. regular expressions are not my strong point ...

freakyjas

4:50 am on Aug 26, 2010 (gmt 0)

10+ Year Member



thanks rocknbil.

heres a sample of the input:

english: (aka $search)
Buy Today
Phone
Outside USA Phone
Mobility

spanish: (aka $replace)
Compre Hoy
Teléfono
Teléfono fuera de los EE UU
Movilidad

the $content is just a standard html page.

does that help at all?

freakyjas

5:39 am on Aug 26, 2010 (gmt 0)

10+ Year Member



i guess i could always use str_replace

$newcontent = str_replace($patterns, $replacements, $content);