简体   繁体   English

如何在PHP中使用jquery / javascript替换作为preg_replace?

[英]How to use jquery/javascript replace as preg_replace in PHP?

The preg_replace function in PHP provides a limit parameter. PHP中的preg_replace函数提供了一个limit参数。 For instance, the first occurrence of medium replace with original, and the second occurrence of medium replace with "type". 例如,第一次出现的媒体替换为原始,第二次出现的媒体替换为“类型”。

$path = "demo\/medium\/Web081112_P001_medium.jpg";
$path = preg_replace ("/medium/","original",$path,1);
$path = preg_replace ("/medium/","type",$path,2);
echo $path;
// output : demo\/original\/Web081112_P001_type.jpg

So, are there any way using JQuery/ JavaScript to implement similar function? 那么,有什么方法可以使用JQuery / JavaScript实现类似的功能? Thanks 谢谢

General solution: 通用解决方案:

var n = 0;
"a a a a a".replace(/a/g, function(match) {
  n++;
  if (n == 2) return "c";
  if (n == 3 || n == 4) return "b";
  return match;
})
// => "a c b b a"

Also, you are mistaken: the second replacement will not happen. 另外,您也弄错了:第二个替换将不会发生。 Limit 2 doesn't say "second occurence", it says "two occurences"; 极限2不说“第二次发生”,而是说“两次发生”。 however, after the first preg_replace you don't have two mediums any more, so the second preg_replace ends up replacing the single one that is left, and then quits in frustration. 但是,在第一个preg_replace之后,您再也没有两个介质了,因此第二个preg_replace最终替换了剩下的单个介质,然后沮丧地退出了。 You could do the same using two single-shot (non-global) replace (or preg_replace ) invocations, without using any limit. 您可以使用两个单次(非全局) replace (或preg_replace )调用来执行相同操作,而无需使用任何限制。

are there any way using jquery/ javascript to implement similar function? 有什么方法可以使用jquery / javascript实现类似的功能?

Use JavaScript's native replace() . 使用JavaScript的本机replace()

By default, replace() will only replace the first occurrence - unless you set the g modifier. 默认情况下,除非您设置g修饰符,否则replace()将仅替换第一次出现的内容。

Example: 例:

path = "demo/medium/Web081112_P001_medium.jpg";
path = path.replace("/medium/", "original");
path = path.replace("medium", "type");

Note: Your code doesn't match your specification. 注意:您的代码与规范不符。 I addressed your specification. 我满足了您的要求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM