2016-07-31 12 views
-1

我有一個字段中包含字段佔位符的字符串。我需要通過佔位符拆分字符串,並將字符串和佔位符返回到單個數組中。使用PHP通過標籤拆分字符串並將每個標籤替換爲唯一值

舉例來說,如果我有字符串:

Ohio is one of the original [s] in the northwest territory. [s] and [s] were also part of the northwest territory. Which states are missing [a]? 

我想看到它分裂成一個數組:

[0] => Ohio is one of the original 
[1] => [s] 
[2] => in the northwest territory. 
[3] => [s] 
[4] => and 
[5] => [s] 
[6] => were also part of the northwest territory. Which states are missing 
[7] => [a] 
[8] => ? 

爲了滿足那些誰認爲我們從來不看說明書,這裏有我試過的幾段代碼......我只是無法獲得上面列出的格式的數組。我最近來的是這個,但它仍然獲得比我在數組的某些部分所需的更多的文本。我承認,我從來沒有成爲REGEX專家,所以你的幫助表示感謝。

我匹配於包含在[]即[A],[B],[E]的任一個字符等

preg_match_all("/(.*?)\[(.)\](.*?)/",$string,$x,PREG_SET_ORDER); 
print_r($x); 
+3

你嘗試什麼嗎?如何http://php.net/manual/en/function.preg-split.php – rjdown

+0

很容易把RTFM扔給別人不是這樣。是的,我一直在玩preg_match,preg_split,preg_match_all和所有三種不同的排列,但我想我只是想念一些簡單的東西。 – LuvnJesus

回答

1

雖然我最初是由厭惡答案從rjdown冒犯,我重新訪問了我的所有例子,並找到了一個可行的選項。包括「-1」是最後的伎倆。由於rjdown

$results =preg_split("/(\[.\])/i",$string, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); 

結果是:

Array 
(
    [0] => Ohio is one of the original 
    [1] => [s] 
    [2] => in the northwest territory. 
    [3] => [s] 
    [4] => and 
    [5] => [s] 
    [6] => were also part of the northwest territory. Which states are missing 
    [7] => [a] 
    [8] => ? 
) 
+0

令人討厭?你發佈的所有內容都是你想要做的,沒有證據表明你已經嘗試過任何解決方案。這不是stackoverflow的工作原理。指向你潛在的有用功能的方向比大多數人會做的更多。通常你會得到一個鏈接到http://stackoverflow.com/help/how-to-ask – rjdown

相關問題