2016-04-27 82 views
2

我有串象下面這樣:如何在PHP中獲取字符串後的字符串?

$str = '/test/test1/test2/test3/testupload/directory/'; 

現在我要取這麼嘗試了一些特定的字符串:

strstr($str, 'test3'); 

但我想針後獲取價值?我能怎麼做?

謝謝。

+5

可能重複[獲取文本後針?](http://stackoverflow.com/questions/2216710/get-text-after-needle) – Dhiraj

+0

爲什麼不拆分字符串,然後挑選最後的數組值? – Abhishek

+0

@BhumiShah在這裏沒有正確或有用的答案嗎? – Andreas

回答

2
$str = '/test/test1/test2/test3/testupload/directory/';   
$new_str = strstr($str, 'test3'); 
// Use this to get string after test3 
$new_str = str_replace('test3', '', $new_str); 
// $new_str value will be '/testupload/directory/' 
0

你可以找出test3指數,然後進行:

<?php 
$str = '/test/test1/test2/test3/testupload/directory/'; 
$find = 'test3'; // Change it to whatever you want to find. 
$index = strpos($str, $find) + strlen($find); 
echo substr($str, $index); // Output: /testupload/directory/ 
?> 

或爆炸()的陣列test3,並找出最後一個元素。

<?php 
$str = '/test/test1/test2/test3/testupload/directory/'; 
$find = 'test3'; // Change it to whatever you want to find. 
$temp = explode($find, $str); 
echo end(explode($find, $str)); 
?> 
0

嘗試

<?php 
$str = '/test/test1/test2/test3/testupload/directory/'; 
$position = stripos($str, "test3"); 
if ($position !== false) { 
    $position += strlen("test3"); 
    $newStr = substr($str, $position); 
    echo "$newStr"; 
} else { 
    echo "String not found"; 
} 
?> 
0

也可以用的preg_match()

preg_match("/test3\/(.*)/", $str, $output); 
Echo $output[1]; 

用的preg_match做它是一條線的工作得到你想要的部分。
該模式搜索test3/後,但/需要轉義\/
然後(.*)表示匹配所有內容直到字符串結束。
輸出[0]將完全匹配「test3/testupload ...」。
輸出[1]只是您想要「testupload/...」的部分。

0

爲什麼不構建幫助函數。

這是我之前做的一個(完全不是藝術攻擊參考)。

/** 
* Return string after needle if it exists. 
* 
* @param string $str 
* @param mixed $needle 
* @param bool $last_occurence 
* @return string 
*/ 
function str_after($str, $needle, $last_occurence = false) 
{ 
    $pos = strpos($str, $needle); 

    if ($pos === false) return $str; 

    return ($last_occurence === false) 
     ? substr($str, $pos + strlen($needle)) 
     : substr($str, strrpos($str, $needle) + 1); 
} 

您可能已經注意到,此功能可讓您選擇在給定針的第一次或最後一次出現後返回內容。因此,這裏的一對夫婦的使用情況:

$animals = 'Animals;cat,dog,fish,bird.'; 

echo str_after($animals, ','); // dog,fish,bird. 

echo str_after($animals, ',', true); // bird. 

我傾向於建立一個全球helpers.php文件,其中包含與此類似的功能,我建議你做同樣的 - 它使事情變得更輕鬆。

相關問題