2015-07-21 133 views
2

這是我的字符串:PHP:如何從字符串中獲取特定單詞

$string="VARHELLO=helloVARWELCOME=123qwa";

我想從字符串中獲得'hello'和'123qwa'。

我的僞代碼是。

 
if /^VARHELLO/ exist 
    get hello(or whatever comes after VARHELLO and before VARWELCOME) 
if /^VARWELCOME/ exist 
    get 123qwa(or whatever comes after VARWELCOME) 

注意:從 'VARHELLO' 和 'VARWELCOME' 值是動態的,所以 'VARHELLO' 可能是 'H3Ll0' 或VARWELCOME可能是 'W3l60m3'。

Example: 
$string="VARHELLO=H3Ll0VARWELCOME=W3l60m3";
+0

看看PHP的[parse_str()](HTTP://www.php。 net/manual/en/function.parse-str.php)函數 –

+0

爲什麼不用像「VARHELLO = H3Ll0&VARWELCOME = W3l60m3」這樣的分隔符分割然後爆炸成一個數組? –

+0

好的如果分隔符是空格? –

回答

4

這裏有一些代碼將把這個字符串解析爲一個更有用的數組。

<?php 
$string="VARHELLO=helloVARWELCOME=123qwa"; 
$parsed = []; 
$parts = explode('VAR', $string); 

foreach($parts AS $part){ 
    if(strlen($part)){ 
     $subParts = explode('=', $part); 
     $parsed[$subParts[0]] = $subParts[1]; 
    } 

} 

var_dump($parsed); 

輸出:

array(2) { 
    ["HELLO"]=> 
    string(5) "hello" 
    ["WELCOME"]=> 
    string(6) "123qwa" 
} 

或者使用替代parse_strhttp://php.net/manual/en/function.parse-str.php

<?php 
$string="VARHELLO=helloVARWELCOME=123qwa"; 
$string = str_replace('VAR', '&', $string); 

var_dump($string); 
parse_str($string); 

var_dump($HELLO); 
var_dump($WELCOME); 

輸出:

string(27) "&HELLO=hello&WELCOME=123qwa" 
string(5) "hello" 
string(6) "123qwa" 
+0

謝謝。你節省了我的時間。 –

+0

不客氣:) – Jessica

+1

我建議不要使用parse_str(),因爲它會污染範圍,並可能引入安全問題:'「VAR&_GET = ...」' –

2

傑西卡的答案是完美的,但如果你想使用preg_match

$string="VARHELLO=helloVARWELCOME=123qwa"; 

preg_match('/VARHELLO=(.*?)VARWELCOME=(.*)/is', $string, $m); 

var_dump($m); 

得到它的結果將是$m[1]$m[2]

array(3) { 
    [0]=> 
    string(31) "VARHELLO=helloVARWELCOME=123qwa" 
    [1]=> 
    string(5) "hello" 
    [2]=> 
    string(6) "123qwa" 

}

+0

謝謝先生。 :) –

+0

@KuhaCoAkawntMo:不客氣。 – Mubin

相關問題