2017-09-25 47 views
-2

我想問一下能否獲得某個特定關鍵字之間的字符串?例如,我有2句這樣的:PHP獲取特定字詞內的一些字符串

I will go to #new bathroom and wash the car# 

結果:bathroom and wash the car

Someone need an #new icebreaker# to hold that problem 

結果:icebreaker

我想使病情得到#new # 任何想法如何之間的所有單詞創造這個?

我迄今爲止代碼:

<?php 

$sentence = "I will go to #new bathroom and wash the car#"; 
$start = strpos($sentence, "#new"); 
//$end = strpos($sentence, "#"); 
$end = 20; //because my strpos still wrong, I define a static number 
$new = substr($sentence, $start, $end); 
echo $new; 

?> 

我的問題是我無法找到一個方法來追逐最後的主題標籤

+2

http://regular-expressions.info – deceze

+1

檢查https://stackoverflow.com/questions/5127322/output-text-in-between-two-words?rq=1 – Saty

+0

@Saty謝謝! –

回答

1

使用正則表達式:

/#new (.+)#/i 
preg_match()

在一起,你會得到你的對手在一個陣列:

<?php 
$string = "Someone need an #new icebreaker# to hold that problem"; 
preg_match("/#new (.+)#/i", $string, $matches); 
var_dump($matches[1]); // icebreaker 

Demo

如果您預計可能有多個匹配項,請使用preg_match_all()來獲取全部匹配項。

+0

謝謝!就像Saty給我的上一個鏈接一樣。 –

1

另一種方法是正則表達式不同的是explode字符串和replace在森new如果你只有一個關鍵字唐塞

這只是工作中的一句話#new

$string = "I will go to #new bathroom and wash the car#"; 
$string1 = "Someone need an #new icebreaker# to hold that problem"; 

function getString($string, $delimiter = '#') 
{ 
    $string_array = explode($delimiter, $string); 
    return str_replace('new ', '', $string_array[1]); 
} 

echo getString($string); 
//bathroom and wash the car 

echo getString($string1); 
//icebreaker 

我想和陣列

$string = [ 
"I will go to #new bathroom and wash the car#", 
"Someone need an #new icebreaker# to hold that problem" 
]; 

function getString($string, $delimiter = '#') 
{ 
    $result = []; 
    foreach ($string as $value) { 
     $string_array = strstr($value, $delimiter) ? explode($delimiter, $value) : []; 
     $result[] = isset($string_array[1]) ? str_replace('new ', '', $string_array[1]) : NULL; 
    } 
    return $result; 
} 

print_r(getString($string)); 


/* 
Array 
(
    [0] => bathroom and wash the car 
    [1] => icebreaker 
) 
*/ 
+0

確保'$ string'中有'$ delimiter',否則'explode()'不起作用,你會得到一個未定義的索引通知。而且,當沒有'#new'時,它仍然會得到兩個shebang之間的東西。最後,當出現奇數個shebang時,它會變得混亂。 – ishegg

+0

@ishegg在第二個片段中,我爲未定義的索引通知提供了一個解決方案...關於奇數個hashtag ... OP說他有句子...我試圖提供其他不同於常規experssion的方式具體案例他出現在問題 –

+0

當然,我同意這是更好的方法!正則表達式應該始終是最後一個選項,因爲它們更昂貴。儘管在這種情況下,另一種方式似乎更復雜。 – ishegg

0

更多的工作可以從結尾搜索「#」, like $ end = strpos($ sentence,「#」,-0);

而不是像你已經擁有子字符串。

$new = substr($sentence, $start, $end); 
1

我爲你的問題寫了下面的代碼,但請記住我自己仍然是初學者。 它的工作原理如何,但我相信有更好的解決方案。

<?php 

$string = "I will go to #new bathroom and wash the car#"; 
$stringArray = str_split($string); 
$output = ''; 
$count = 0; 

foreach($stringArray as $letter){ 

    if($count == 0 && $letter == '#'){ 
     $count = 1; 
    } elseif($count == 1){ 
     if($letter != '#'){ 
      $output .= $letter; 
     } else { 
      $count = 2; 
     } 
    } 

} 

echo $output; 

?> 

希望這有助於:)

相關問題