【问题标题】:Replace anything regex php替换任何正则表达式 php
【发布时间】:2014-10-27 03:32:54
【问题描述】:

我在 php 中有这个正则表达式

$array_item_aux = str_replace('/.*PUBMED=/',"",$array_item);

它应该替换这个文本 (-|ENSR00001252129|RegulatoryFeature|regulatory_region_variant|-|-|-|-|-|PUBMED=21499247

有了这个

21499247

我做错了什么

【问题讨论】:

  • 对于它的价值,惰性匹配是不必要的(.*? 而不是你的.*) - 不完全确定人们为什么建议这个......虽然它肯定不会伤害.归根结底,下面提到的功能变化是这里的主要问题。
  • 惰性匹配适用于多个 PUBMED= 在应用它的文本中多次出现的情况,因为 .* 确实匹配。但这取决于输入。

标签: php regex str-replace


【解决方案1】:

或者,如果你显示的字符串是整个字符串,你可以使用explode:

$array_item_aux = explode('PUBMED=', $array_item)[1];

如果您的 PHP 版本对于此语法来说太旧 (

$tmp = explode('PUBMED=', $array_item);
$array_item_aux = $tmp[1];

或者正如@Sam 建议的那样:

list(, $array_item_aux) = explode('PUBMED=', $array_item);

【讨论】:

  • 这个答案可能应该包括关于 PHP 版本可用性的注释/警告。(但当然是一个很好的替代方法!)
  • 只是给对此答案感兴趣的人的注释:“太老了”
  • 旧 PHP 的另一种选择是 list(, $array_item_aux) = explode('PUBMED=', $array_item);
  • @Sam: 语法很好,我会添加它
【解决方案2】:

str_replace 不使用正则表达式,使用preg_replace

$array_item_aux = preg_replace('/.*?PUBMED=/', "", $array_item);

【讨论】:

    【解决方案3】:

    您应该通过添加? 来创建.* lazy instead of a greedy;但您的主要问题是str_replace() 不允许使用正则表达式进行搜索,而是使用preg_replace()

    $array_item_aux = preg_replace('/.*?PUBMED=/', '', $array_item);
    

    【讨论】:

      猜你喜欢
      • 2013-12-09
      • 2011-02-21
      • 1970-01-01
      • 2022-06-15
      • 2014-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-29
      相关资源
      最近更新 更多