2014-02-11 293 views
0

讓潛在括號說我有一個變種$text
字符串替換與字符串

Lorem存有悲坐阿梅德。 John Doe Ut tincidunt,elit ut sodales molestie。

和VAR $name

李四

我需要發現的$name所有出現在$text,並添加周圍的HREF。
我現在用str_replace做什麼。

但是如果名稱中有括號?
讓說VAR $text這個樣子的,而不是:

Lorem存有悲坐阿梅德。 John(Doe)Ut tincidunt,elit ut sodales molestie。

Lorem存有悲坐阿梅德。 (John)Doe Ut tincidunt,elit ut sodales molestie。

如何用圓括號找到$name

+0

被括號中的唯一可能的變化? – 2014-02-11 18:49:33

+0

您可以使用正則表達式,但首先您必須定義確切的要求,括號的類型等。 – jeroen

+0

@圓括號是唯一可能的變體。 –

回答

1
$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); 
2

按名字和姓氏分割名稱。

$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 
); 
+2

我想你的意思是'preg_replace' –

+0

不幸的是,我不能拆分名稱,因爲有人可能被命名爲例:「Ryan Nugent Hopkins」 –

+1

那麼你可以把搜索字符串放在一個foreach循環中,使其更具動態性。 –

0

另一個版本,使用時只需使preg_split

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

另一posibility使用ucwords

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

然後

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

作品也可以與其它類型的分隔符[{()}]等...