【问题标题】:String replacement with potential parentheses in the string用字符串中的潜在括号替换字符串
【发布时间】:2014-03-09 17:58:17
【问题描述】:

假设我有一个 var $text:

Lorem ipsum dolor sit amet。 John Doe Ut tincidunt, elit ut sodales 性骚扰。

还有一个变量$name:

约翰·多伊

我需要找出所有出现在$text 中的$name 并在其周围添加一个href。
我目前对 str_replace 所做的事情。

但是,如果名称中有括号怎么办?
假设 var $text 看起来像这样:

Lorem ipsum dolor sit amet。 John (Doe) Ut tincidunt, elit ut sodales 性骚扰。

Lorem ipsum dolor sit amet。 (John) Doe Ut tincidunt, elit ut sodales 性骚扰。

我怎样才能找到带括号的$name

【问题讨论】:

  • 括号是唯一可能的变化吗?
  • 你可以使用正则表达式,但首先你必须定义确切的要求,什么样的括号等等。
  • @Dagon 括号是唯一可能的变体。
  • @jeroen 括号的类型将与示例中提供的完全相同。不允许其他任何事情。

标签: php regex string replace


【解决方案1】:

按名字和姓氏分开名字。

$split = explode(' ', $name);
$first = $split[0];
$last  = $split[1];


preg_replace(
  "/(\(?($first)\)? \(?($last)\))/"
, $replacement
, $text
);

更动态的方法

// split name string into sub-names
$split = explode(' ', $name);

// initiate the search string 
$search = '';

// loop thru each name
// solves the multiple last or middle name problem     
foreach ($split as $name) {
  // build the search regexp for each name
  $search .= " \(?$name\)?";
}

// remove first space character
$search = substr($search, 1);

// preg_replace() returns the string after its replaced
// note: $replacement isn't defined, left it for you :)

// note: the replacement will be lost if you don't
//  print/echo/return/assign this statement.
preg_replace(
  "/($search)/"
, $replacement
, $text
);

【讨论】:

  • 我想你的意思是preg_replace
  • 很遗憾,我不能拆分名字,因为有人可以命名例如:“Ryan Nugent Hopkins”
  • 那么您可以将搜索字符串放在 foreach 循环中以使其更具动态性。
【解决方案2】:

另一个只使用 preg_split 的版本

$split=preg_split('/\s+/', $name);
$frst=$split[0];
$mid=$split[1];
$lst=$split[2];

另一种可能性是使用 ucwords

$split=ucwords($name);
$frst=$split[0];
$mid=$split[1];
$lst=$split[2];

然后

preg_replace('.?$frst.? .?$mid.? .?$lst.?',$replacement,$text);

也适用于其他类型的分隔符 [{()}] 等 ...

【讨论】:

    【解决方案3】:
    $text = "Lorem ipsum dolor sit amet. (John) Doe Ut tincidunt, elit ut sodales molestie.";
    
    $name = "John Doe";
    
    function createUrl($matches) {
        $name = $matches[0];
        $url = str_replace(['(', ')'], '', $matches[0]);
        return "<a href='index.php?name={$url}'>{$name}</a>";
    }
    $pattern = str_replace(' ', '\)? \(?', $name);
    echo preg_replace_callback("/(\(?$pattern\)?)/", 'createUrl', $text);
    

    【讨论】:

      最近更新 更多