2011-04-19 23 views
1
string string {format mat=34/} string string string string string string string string 

string string {format mat=34/} string string string string string string string string 
  1. $圖案= 「/ {格式並[a-Z0-9 = \ S] * \ /}/I」;PHP - 正則表達式 - 多匹配結果

    str_replace($ pattern,'test',$ strings);

    它將替換字符串中的所有格式,我只想替換第一個「格式」,並刪除所有其他「格式」。怎麼樣 ?

  2. 當匹配結果是「{format mat = 34 /}」時。我想查找以「mat =」開頭的字符串。

所以我有這個

$string = "{format mat=34/}"; 
$pattern = "/^mat=[0-9]*/"; // result is null 
$pattern = "/mat=[0-9]*/"; // ok, but also effect with "{format wrongformat=34/}" 

如何匹配開頭的字符串 「墊=」

回答

0

關於第一個問題,你可以使用某種str_replace_once()

例發現於PHP manual comments

function str_replace_once($str_pattern, $str_replacement, $string) 
{ 
    if (strpos($string, $str_pattern) !== false) 
    { 
    $occurrence = strpos($string, $str_pattern); 
    return substr_replace($string, $str_replacement, strpos($string, $str_pattern), strlen($str_pattern)); 
    } 
    return $string; 
} 

要刪除所有其他比賽中,看到謝爾蓋的回答:)

對於你的第二個問題:

$string = '{format mat=34/}'; 
preg_match("|\s(mat=[0-9]+)/\}$|", $string, $matches); 
print_r($matches); // $matches[1] contains 'mat=34' 
+0

感謝,並以 「/ \ SMAT = [0-9] * /」 是足夠 – Chameron 2011-04-19 17:46:13

0
  1. 沒有str_replace函數,但preg_replace函數中,取代了的preg_replace限制數量$極限參數 - 剛剛成立它爲1.
  2. 使用\ b - 字邊界。

    $ pattern ='/ \ bmat = [0-9] * /';

+0

感謝 「\ B」,我會嘗試:d – Chameron 2011-04-19 17:49:06

1

(你的問題的第一部分)

你可以匹配這個表達式,它使用{N}第一格式指定只匹配第一次出現

$pattern = "(^.*?\{format[a-z0-9=\s]*\}.){1}" 

開始從第一個角色開始,直到第一個格式進行非貪婪匹配,然後纔會發生{1}發生的情況。

運行此操作來完成初始替換,然後後綴對其餘格式執行正常的str_replace。

+0

感謝您的建議。 http://www.regular-expressions.info/continue.html怎麼樣? – Chameron 2011-04-19 17:53:23

1

這裏是您的解決方案:

$string = "string {format mat=34/} string string string {format mat=34/} string string string string {format mat=34/} string string string string string "; 

// replace first match with 'test' 
$string = preg_replace('/\{format mat=[\d]*\/\}/', 'test', $string, 1); 

// remove all other matches 
$string = preg_replace('/\{format mat=[\d]*\/\}/', '', $string); 
+0

謝謝,我會試試看 – Chameron 2011-04-19 17:48:22