2011-10-13 27 views
1

如何獲取放置在兩個星號內的字符串 - * - 像StackOverflow這樣?如何獲取放置在兩個星號*之間的字符串*像StackOverflow

例如,

$string_1 = 'this is the *string I want to display only*'; 

$string_2 = 'this is the * string I want to display only *'; 

注意有第二串空間。

我想回到這個只,

string I want to display only 

使用正則表達式是我能想到的...任何想法?

+3

這是有些低估。如果字符串中包含兩個以上的'*',您希望發生什麼? – Mankarse

+0

好問題!我想那麼它應該返回整個字符串與星星。 – laukok

+0

這是StAckOverflow。它位於每頁的頂部;我不確定你是如何拼錯它兩次的。 :) –

回答

0

嘗試此

$string_1 = 'this is the *string I want to display only*'; 

    if(preg_match_all('/\*(.*?)\*/',$string_1,$match)) {    
      var_dump($match[1]);    
    } 
+1

這不會像坦杜的答案一樣工作。字符串'hello * cruel * * world *'只會返回一個結果:'殘酷* *世界'。 – slebetman

0

正則表達式溶液

$string_2 = 'this is the * string I want to display only *'; 
$pattern = "/(\*)+[\s]*[a-zA-Z\s]*[\s]*(\*)+/"; 
preg_match($pattern, $string_2, $matches); 
echo $matches[0]; 

PHP字符串函數解決方案,使用:strpos(),strlen的()和SUBSTR()

$string = 'this is the * string I want to display only *'; 
$findme = '*'; 
$pos = strpos($string, $findme); // get first '*' position 
if ($pos !== FALSE) { 
    // a new partial string starts from $pos to the end of the input string 
    $part = substr($string,$pos+1,strlen($string)); 
    // a new partial string starts from the beginning of $part to the first occurrence of '*' in $part 
    echo substr($part,0,strpos($part, $findme)); 
} 
+0

謝謝你:) – laukok

2

你可以做這個無線th簡單的正則表達式:

這將存儲變量matches中的所有匹配項。

$string = "This string *has more* than one *asterisk group*"; 
preg_match_all('/\*([^*]+)\*/', $string, $matches); 
var_dump($matches[1]); 
相關問題