string manipulation preg_replace or str_replace
I need to replace a word with another word. But
$var= str_replace($linklabel[$k], $linklabelmod[$k], $var);
is not giving the desired result. For example i have a string
$var="the theory of them thesis";
$linklabel[1]="the";
$linklabelmod[1]="hhh";
What i need is, i just want to replace the word "the". But since "the" is repeated in "theory" "thesis" and "them", all those starting three letters are also getting replaced. Then output becomes $var="hhh hhhory of hhhm hhhsis";//wrong But i need the output $var="hhh theory of them thesis";//write I am bad at explaining a question, plz excuse me...
Thanks in advance....
From what I (paxdiablo) can gather from the OP's comments, this is the code following modifications (still claimed not to work):
foreach($xpath->query('//a') as $element) {
$linklabel[] = $element->textContent;
$link[] = $element->getAttribute("href");
$i=$i+1;
}
for($k=0;$k<$i;$k++) {
$linklabelmod[$k] = str_replace($linklabel[$k], $linklabel[$k]."[$k]", $linklabel[$k]);
$var = preg_replace ('/\b'.pre开发者_开发问答g_quote($linklabel[$k]).'\b/', $linklabelmod[$k], $var);
}
print $var; //printing web page
The normal way of doing what you want is to use a regular expression replace with word boundaries:
$var = preg_replace ('/\bthe\b/', 'hhh', $var);
or:
$var = preg_replace ('/\b'.preg_quote($linklabel[$k]).'\b/', $linklabelmod[$k], $var);
Insert white space :) if you want to use str_replace function
php > $var = "the theory of them thesis";
php > $var = str_replace(array(" the ", "the "), 'hhh', $var);
php > echo $var;
Well i would always advise in using str_replace over preg_replace but in this case you might have to.
<?php
$k = 1;
$var="the theory of them thesis";
$linklabel[1]="the";
$linklabelmod[1]="hhh";
$var = preg_replace('/\b'.preg_quote($linklabel[$k]).'\b/i',$linklabelmod[$k], $var);
?>
Dont forget to preg_qoute the text to minimize the amount of errors
$var = "the theory of them thesis";
$linklabel[1] = "the";
$linklabelmod[1] = "hhh";
$var = str_replace( " " . $linklabel[1] . " ",
" " . $linklabelmod[1] . " ",
" " . $var . " ");
$var = trim($var);
精彩评论