PHP匹配并替换整个单词

时间:2016-01-13 12:07:28

标签: php preg-replace

您好我正在用不同的值替换某些名称。以下是我要替换"@size-name""@size"的值。但问题是我的代码仅替换大小而注释名称例如

@size = "replaceword"
@size-name = "replaceword2"

但它取代了

@size ="replaceword"
@size-name = "replaceword2-name"

如何替换整个单词而不是其中的一部分是我的代码

$tempOutQuery = preg_replace("/(\b($key)\b)/i" , $value  , $tempOutQuery);
   $tempOutQuery=  str_replace("@".$key ,$value ,$tempOutQuery); 

两个代码都无效

我的完整代码

$val= "Hi I want @size dress which is @size-name";

$tempOutQuery = preg_replace("/(\b(size)\b)/i" ,"replaceword", $tempOutQuery);
$tempOutQuery = preg_replace("/(\b(size-name)\b)/i" ,"replaceword2", $tempOutQuery);

3 个答案:

答案 0 :(得分:1)

如果你可以在不使用规则表达式的情况下进行替换,那么我建议对数组使用标准str_replace()

$val= "Hi i want @size dress which is @size-name";

$search  = array('size-name', 'size');
$replace = array('replaceword2', 'replaceword');

$result = str_replace($search, $replace, $val);
  

搜索和替换字符串的顺序非常重要!   您应该注意首先替换长搜索字符串,然后再替换短字符串。

答案 1 :(得分:0)

以下是使用preg_replace_callback的另一种选择。它实际上与Gennadiy的方法非常相似。唯一真正的区别在于它使用了PHP的preg方面(而且还有很多工作)。但这是剥夺众所周知的猫的另一种方式。

<?php

// SET OUR DEFAULT STRING
$string = 'Hi I want @size suit which is @size-name';

// LOOK FOR EITHER size-name OR size AND IF YOU FIND IT ...
// RUN THE FUNCTION 'replace_sizes'
$string = preg_replace_callback('~@(size-name|size)~', 'replace_sizes', $string);

// PRINT OUT OUR MODIFIED STRING
print $string;




// THIS IS THE FUNCTION THAT WILL BE RUN EVERY TIME A MATCH IS FOUND
// EITHER 'size' OR 'size-name' WILL BE STORED IN $m[1]
function replace_sizes($m) {

    // SET UP AN ARRAY THAT HAS OUR POTENTIAL MATCHES AS KEYS
    // AND THE TEXT WE WANT TO REPLACE WITH AS THE VALUE
    $size_text_array = array('size-name' => 'replaceword2', 'size' => 'replaceword');

    // RETURN WHATEVER THE VALUE IS BASED ON THE KEY
    return $size_text_array[$m[1]];

}

这将打印出来:

Hi I want replaceword suit which is replaceword2

这是一个有效的演示:

http://ideone.com/njNTbB

答案 2 :(得分:0)

您可以尝试使用pre_replace()替换PHP中数组中的整个单词,如下所示。

var CartSchema = new Schema({
  products: [{
    product: { type: Schema.ObjectId, ref : 'Product' },
    quantity: { type: Number, default: 1}
  }],
  totalItems: { type: Number, default: 0},
  message: { type: String },
  client: { type : Schema.ObjectId, ref : 'User' },
  time: { type: Date, default: new Date()},
  session: { type: String }
});

查看整个you can check the image here