RustBeard
RustBeard

Reputation: 79

preg_replace in for loop

I want to insert   symbol after some conjunctions. $cont variable has some text. My code:

$conjs = array ('i', 'a', 'w'); 
$size = sizeof($conjs);
$replacm = ' $1 ';

for ($i=0; $i < $size; $i++){
    $pattern = '/\s(' . $conjs[$i] . ')(\s)/';
    $replaced = preg_replace($pattern, $replacm, $cont);
}

print $replaced;

This returns $cont text changed only with last array element ("w"). What I'm doing wrong?

Upvotes: 1

Views: 1283

Answers (3)

Danon
Danon

Reputation: 2973

This method already exists in T-Regx tool and it's called chainedReplac().

Pattern::compose(['\si(\s)', '\sa(\s)', '\sw(\s)'])->chainedReplace($cont)->with("'$1&nbsp;");

Not to mention you could just do

Pattern::of('\s[iaw](\s)')->replace($cont)->all()->with('$1&nbsp;');

Upvotes: 0

Santosh Jagtap
Santosh Jagtap

Reputation: 1075

Working example

$cont = 'any text word';
$conjs = array ('i', 'a', 'w'); 
$size = sizeof($conjs);
$replacm = '$';

for ($i=0; $i < $size; $i++){
    $pattern = '/' . $conjs[$i] . '/';    
    $cont= preg_replace($pattern, $replacm, $cont);
}

print $cont;

Upvotes: 0

Clyff
Clyff

Reputation: 4076

try change your for to:

for ($i=0; $i < $size; $i++){
    $pattern = '/\s(' . $conjs[$i] . ')(\s)/';
    $cont= preg_replace($pattern, $replacm, $cont);
}    

Upvotes: 1

Related Questions