正则表达式 - 将数字和字符串的组合替换为另一个字符串

时间:2017-02-24 16:23:35

标签: php jquery regex replace

我需要用[替换字符串]

替换所有[任意数字]和[特定字符串]

例如,如果在段落中找到 195 apples 10 apples 等字符串,我需要将其替换为 10 Oranges

示例段落:第一个篮子里有195个苹果,第二个篮子里有10个苹果。

应用正则表达式替换后,我应该得到一个结果 结果:第一个篮子里有10个橘子,第二个篮子里有10个橘子。

在Jquery中,我使用了

 myString.replaceAll("[(?i)string]", "anotherstring"); 

需要在PHP和Jquery中执行此操作。

任何人都可以帮助我吗?感谢

4 个答案:

答案 0 :(得分:2)

怎么样:



 
 var myString = 'There are 195 apples in the first basket and 10 apples in the second basket.';
myString = myString.replace("/(?i)\d+\s+apples\b/g", "10 Oranges");
console.log(myString);




答案 1 :(得分:1)

搜索\d{1,}\s+(apples)

替换10 Oranges

答案 2 :(得分:1)

尝试使用以下正则表达式

(\d+\s(\w+))

** 您可以将\w+替换为所需的字符串

请参阅demo / explanation

<强>的JavaScript

var str = "There are 195 apples in the first basket and 10 apples in the second basket.";
var result = str.replace(/(\d+\s(\w+))/ig, "10 Oranges");
console.log(result);

<强> PHP

$re = '/(\d+\s(\w+))/';
$str = 'There are 195 apples in the first basket and 10 apples in the second basket.';
$subst = '10 Oranges';
$result = preg_replace($re, $subst, $str);
echo $result;

答案 3 :(得分:0)

这有效

PHP

$re = '/(\d+\s((apples\b|apple\b)+))/';
$str = '195 apples in the first basket and 0 apple but 1 applex';
$subst = '10 Oranges';
$result = preg_replace($re, $subst, $str);
echo $result;

JQuery

var text1 = "10 apples is good";
var rrr = "10 Oranges";
var str = "There are 195 apple in the first basket and 10 apples in the second basket.1 apple";
var result = str.replace(/(\d+\s((apples\b|apple\b)+))/ig,"10 Oranges");
console.log(result);