【问题标题】:Remove everything between two quote tags删除两个引号标签之间的所有内容
【发布时间】:2015-12-18 13:14:44
【问题描述】:

文本包含一些带有随机数的引号。

见:

$string = '[quote="Member123":hk1f9ynv]This is the quote Text  and we want remove it.[/quote:hk1f9ynv]

Here is the anwser to the quote. 

[quote:hk1f9ynv]Here is another quote, we want remove it too.[/quote:hk1f9ynv]

Thank you very much. Good job!';

编号:hk1f9ynv 存储在数据库中,是随机的。

输出应如下所示:

这里是引用的答案。非常感谢。干得好!

我在堆栈上尝试了许多解决方案。似乎没有任何效果。示例:

preg_replace('/\[[^>]*\]/', '', $string); 
preg_replace('\[/?abc.*?\]', '', $string);

非常感谢。

【问题讨论】:

  • 您尝试过类似preg_replace('\[/?quote\:[a-zA-Z0-9]+\]', '', $string); 的方法吗?我不确定'/' 你可能也需要使用'\'。 Obvisouly 你可以用你想要的替换 'quote'。
  • 尝试了这两个选项。结果 --> 分隔符不能是字母数字或反斜杠
  • 对不起!我忘了在结尾/开始时添加“/”。您必须添加它。
  • 这样吗? preg_replace('[/?quote\:[a-zA-Z0-9]+]/', '', $string);
  • 不,像这样:preg_replace('/\[/?quote\:[a-zA-Z0-9]+\]/', '', $string);?

标签: php regex replace preg-replace


【解决方案1】:

preg_replace 的两种可能方法:

第一个忽略引用标签的id:

~\[quote\b [^]]* ]
 [^[]*+
 (?: (?:\[ (?!/?quote\b) | (?R) ) [^[]* )*+
 \[/quote\b [^]]* ]~x

demo

第二个捕获id并使用它来查找结束标记:

~\[quote\b [^]:]* : (?<id>[^:]*) ]
 .*? # or: [^[]*+ (?:\[(?!\[/quote\b [^]:]* : \g{id} ])[^[]*)*+
 \[/quote\b [^]:]* : \g{id} ]~xs

demo

这两种模式旨在处理嵌套标签。

【讨论】:

  • 两者都像一个魅力。非常感谢您。哪个最好选择?
  • @user2057781:在我看来,第一个。因为它比第二个需要更少的步骤,并且即使没有 id 也可以工作。
  • 拯救了我的一天@casimir。非常好! :) 再次感谢 :) - 以及所有其他人也为您投入时间。
【解决方案2】:

你为什么不直接使用 $string.substr(0, $string.indexOf("]")) 来获取开始标签

【讨论】:

  • 谢谢。回声 $string.substr(0, $string.indexOf("]"));给出 --> 调用未定义的函数 indexof()
  • 不知道 php 是什么。可能是 instr 或 index
  • indexOf 在 php 中是 strpos()information here
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-21
  • 2012-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多