1

以下の例のように、コンテンツに複数の equals が含まれています。PHP関数は、キーが等号の前のテキストであり、値がその後にある配列として、すべての等号を解析できるようにする必要がありますか?

Lorem ipsum id="the id" dolor sit amet, consectetur name="the name" adipisicing elit, sed do type="the type" eiusmod tempor incididunt ut labe et dolore magna aliqua.

そして、結果は次のようになります。

Array ( 
    [id]   => the id
    [name] => the name
    [type] => the type
)
4

2 に答える 2

2

その文字列内のすべてのインスタンスをキャッチするには、 preg_match_allを使用します。

preg_match_all('/([^\s]*?)="([^"]*?)"/',$text, $matches);

必要な変数を見つけて、それらを と の 2 つの配列に設定し$matches[1]ます$matches[2]forまたはforeachループが必要な場合は、それらを新しい配列に入れることができます。

コードパッドで例を作成しました。見たい場合は、こちら.

于 2012-10-07T04:40:28.913 に答える
2
$string; // This is the string you already have.

$matches = array(); // This will be the array of matched strings.

preg_match_all('/\s[^=]+="[^"]+"/', $string, $matches);

$returnArray = array();
foreach ($matches as $match) { // Check through each match.
    $results = explode('=', $match); // Separate the string into key and value by '=' as delimiter.
    $returnArray[$results[0]] = trim($results[1], '"'); // Load key and value into array.
}
print_r($returnArray);
于 2012-10-07T04:41:46.677 に答える