Reputation: 79
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
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 ");
Not to mention you could just do
Pattern::of('\s[iaw](\s)')->replace($cont)->all()->with('$1 ');
Upvotes: 0
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
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