0

私はsubstrstrrposでstrrchrPHP関数を使用して、次のようなフルパスの文字列でファイル名を検索していました。

/images/onepiece.jpgはonepiece.jpgを返します

しかし今、私は最後の「/」ではなく最後の次の「/」を見つける関数が必要です: /images/anime/onepiece.jpgはanime/onepiece.jpgまたは/anime/onepiece.jpgを返します そしてstrrchrとして-1はしませんうまくいかない、hehehe :)、どうすればそれを達成できますか?

[解決済み]@middaparkaと@ShaktiSinghが言ったようにPHPpathinfo()を使用して、MySQLデータベースから画像文字列を取得する方法を変更しました。私の当初の意図どおり、サブフォルダーを含めることができるようになりました。

<?php
/*
 * pathinfo() parameters:
 * PATHINFO_DIRNAME = 1
 * PATHINFO_BASENAME = 2
 * PATHINFO_EXTENSION = 4
 * PATHINFO_FILENAME = 8
 * */
    $slash = '/';
    $mainpath = 'store/image/';
    $thumbspath = 'cache/';
    $path = $imgsrow->photo; //gets the string containing the partial path and the name of the file from the database
    $dirname = pathinfo($path, 1); //gets the partial directory string
    $basename = pathinfo($path, 2); //gets the name of the file with the extension
    $extension = pathinfo($path, 4); //gets the extension of the file
    $filename = pathinfo($path, 8); //gets the name of the file
    $dims = '-100x100.'; //string of size of the file to append to the file name
    $image = $mainpath . $path; //mainpath + path is the full string for the original/full size file
    $thumbs = $mainpath . $thumbspath . $dirname . $slash . $filename . $dims . $extension; //string to point to the thumb image generated from the full size file
?>
    <img src="<?= $thumbs; ?>" width="100" height="100" alt="<?= $row->description; ?>" />
    <br />
    <img src="<?= $image; ?>" width="500" height="500" alt="<?= $row->description; ?>" />
4

4 に答える 4

1

正直なところ、pathinfo関数またはdirname関数を使用してディレクトリパスを分解する方がはるかに簡単です。

例えば:

$filename = pathinfo('/images/onepiece.jpg', PATHINFO_BASENAME);
$directory = dirname('/images/onepiece.jpg');

必要なものを取得するには、これらを組み合わせて使用​​する必要があるかもしれませんが、少なくともOSは「安全」です(つまり、Linux / LinuxとWindowsの両方のパススタイルを処理します)。

あなたが抱えている特定の問題に関しては、次のクロスプラットフォームソリューションを使用して必要なものを入手できるはずです。

<?php
    $sourcePath = '/images/anime/onepiece.jpg';

    $filename = pathinfo($sourcePath, PATHINFO_BASENAME);
    $directories = explode(DIRECTORY_SEPARATOR, pathinfo($sourcePath, PATHINFO_DIRNAME));

    echo $directories[count($directories) -1] . DIRECTORY_SEPARATOR . $filename;
?>
于 2011-03-20T17:01:35.330 に答える
1

explodeパスをセグメントに分割するために使用することをお勧めします。

$segments = explode('/', $path);

次に、を使用$segments[count($segments)-1]して最後のパスセグメントを取得できます。

そして、最後の2つのセグメントについては、を使用array_sliceimplodeてそれらを元に戻すことができます。

$lastTwoSegments = implode('/', array_slice($segments, -2));
于 2011-03-20T17:46:24.570 に答える
0

pathinfo関数を使用する必要があります

pathinfo ($path, PATHINFO_FILENAME );
于 2011-03-20T17:01:11.247 に答える
0

おい、あなたが見つけたい文字列を保持するために一時的な文字列を作るだけです。最後のオカレンスを見つけ、それをxなどの何かに置き換えてから、最後から2番目のオカレンスである新しい最後のオカレンスを見つけます。

于 2011-03-20T17:18:08.323 に答える