1

以下のコードとコメントを読んで、私がやろうとしていることを確認してください。段落で説明するのは難しいです。

$url_fixx = 'home/sublink/group-view/product/catview1'; 
// What my variable holds. MY GOAL IS: I want to omit group-view, product and catview1 from this so I use the trick below. 

catviewの最後に乱数があるので、以下のコードを使用して最後の番号を見つけます。この場合、「catview1」が出力されます。

$string = $url_fixx;
$matches = array();
if (preg_match('#(catview\d+)$#', $string, $matches)) {
    $catViewCatch = ($matches[1]);
 }
// I got this from http://stackoverflow.com/a/1450969/1567428

$url_fixx = str_replace( array( 'group-view/', 'product', 'catview1' ), '', $url_fixx );
// this outputs what I want. 

私の質問は:

//When I replace "catview1" with $catViewCatch, the whole str_replace doesnt work. 
$url_fixx = str_replace( array( 'group-view/', 'product', $catViewCatch), '', $url_fixx );

何故ですか?そして、私は何が間違っているのですか?

PS:また私のURLは時々このようなものに変わります。
$ url_fixx ='home / sublink / group-view / anotuer-sublink / 123-article'

どうすればこれらすべてに取り組むことができますか?

4

1 に答える 1

3

どちらの例もまったく同じものを出力します。以下のコードはこれを示しています。

<?php
$url_fixx = 'home/sublink/group-view/product/catview1';

$string = $url_fixx;
$matches = array();
if (preg_match('#(catview\d+)$#', $string, $matches)) {
    $catViewCatch = ($matches[1]);
}
echo str_replace( array( 'group-view/', 'product', 'catview1' ), '', $url_fixx );
echo '<br />';
echo str_replace( array( 'group-view/', 'product', $catViewCatch), '', $url_fixx );
?>

また、より少ないコードでタスクを実行できるため、代わりにpreg_replaceの使用を検討することもできます。

echo preg_replace('#group-view/product/catview[0-9]+#','',$url_fixx);
于 2012-09-05T01:24:36.283 に答える