Eddie D.
Eddie D.

Reputation: 145

preg_replace for words containing space doesn't work

it's not working for words containing spaces, it works for single words

if possible changing the words from array to bold

the real code

$_POST['descricao'] = "parede hidráulica: teste de parede hidráulica";

$palavras = array("/\bparede hidráulica cozinha\b/i",
"/\bparede área de serviço\b/i",
"/\bparede area de serviço\b/i",
"/\bparede hidraulica cozinha\b/i",
"/\bparede hidráulica\b/i",
"/\bparede hidraulica\b/i",
"/\bparede box\b/i",
"/\btorneira\b/i",
"/\bbancada\b/i",
"/\bsoleira\b/i",
"/\bbaguete\b/i",
"/\brodapé\b/i",
"/\brodape\b/i",
"/\bparede\b/i");

$maiusculas = array_map('mb_strtoupper', $palavras);
$maiusculas = str_ireplace('\b/i', '', $maiusculas);
$maiusculas = str_ireplace('/\b', '', $maiusculas);

$_POST['descricao'] = preg_replace($palavras, $maiusculas, $_POST['descricao'], 1);

output: PAREDE HIDRÁULICA: teste de PAREDE HIDRÁULICA

correct output: PAREDE HIDRÁULICA: teste de parede hidráulica

Upvotes: 1

Views: 368

Answers (3)

Eddie D.
Eddie D.

Reputation: 145

it was solved like this, i've changed my need and using this regex it matches with double words if the word is in uppercase

$_POST['descicao'] = 'UNITED STATES test';
$_POST['descricao'] = preg_replace("/\b([A-Z]{2,}(\s[A-Z]{2,})?)\b/", "<b>$1</b>"

output: <b>UNITED STATES</b> test

Upvotes: 0

Benjamin Toueg
Benjamin Toueg

Reputation: 10877

What if you remove the count argument at the end of this line:

$_POST['descricao'] = preg_replace($palavras, $maiusculas, $_POST['descricao']);

This would give you:

PAREDE HIDRáULICA: teste de PAREDE HIDRáULICA

instead of:

PAREDE HIDRáULICA: teste de parede hidráulica

However, your code is behaving exactly as expected.

If it doesn't suit you, you should provide us your expected output, otherwise we can't help you.

Upvotes: 0

anubhava
anubhava

Reputation: 786291

First argument of preg_replace function is regex (or an array of regex).

I believe it should be:

$arr = array("/\bred apple\b/i", "/\bgreen lemon\b/i");
$arr2 = array("RED APPLE", "GREEN LEMON");

$repl = preg_replace($arr, $arr2, $string, 1);

Upvotes: 1

Related Questions