2016-11-03 135 views
-1

我想從具有分隔符的字符串中刪除子字符串。如何從字符串中提取帶有分隔符的子字符串php

例子:

$string = "Hi, I want to buy an [apple] and a [banana]."; 

如何獲得「蘋果」和「香蕉」出這個字符串,然後以數組?而字符串的其他部分「嗨,我想在另一個陣列中購買」和「和」。

我很抱歉如果這個問題已經得到解答。我搜索了這個網站,找不到任何能幫助我的東西。每種情況都有所不同。

+0

你是什麼意思_和array_中字符串的其他部分?你希望單詞是數組中的值嗎? – AbraCadaver

+0

對不起。沒有看到問題。我想要另一個數組中的短語部分。所以「嗨,我想買一個」,「和一個」,「。」 –

+0

有質量答案的人將回顧你的問題歷史,只是FYI – AbraCadaver

回答

0
preg_match_all('(?<=\[)([a-z])*(?=\])', $string, $matches); 

應該做你想做的。 $matches將是每個比賽的陣列。

1

你可以使用preg_split()這樣的:

<?php 
$pattern = '/[\[\]]/'; // Split on either [ or ] 
$string = "Hi, I want to buy an [apple] and a [banana]."; 
echo print_r(preg_split($pattern, $string), true); 

,輸出:

Array 
(
    [0] => Hi, I want to buy an 
    [1] => apple 
    [2] => and a 
    [3] => banana 
    [4] => . 
) 

可以剪裁的空白,如果你喜歡和/或忽略最終的句號。

+0

謝謝戴夫!這看起來完全像我想要的。去嘗試一下! –

+0

@WandaEmbar認爲你想要他們在一個數組中,然後在另一個數組中的「其他人」? – AbraCadaver

+0

@WandaEmbar可能想回應問題的意見,要求澄清。 – AbraCadaver

0

我想你想的話作爲數組中的值:使用preg_grep()

  • 找到

    $words = explode(' ', $string); 
    $result = preg_grep('/\[[^\]]+\]/', $words); 
    $others = array_diff($words, $result); 
    
    • 創建一個空間
    • 使用正則表達式使用explode()找到[somethings]字的數組所有字的差異和[somethings]使用array_diff(),這將是字符串的「其他」部分
  • 相關問題