2016-04-27 20 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

も、それはあなたがしたい部分を得るために1行の仕事だとするpreg_matchするpreg_match()

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

で行うことができます試してみてください。
パターンの後に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ファイルを作成する傾向があるが、私はあなたが同じことを行うお勧めします - それは物事そんなに簡単になります。

関連する問題