简体   繁体   English

如何在某些字符后从字符串的开头和结尾删除?

[英]How to remove from starting and from end of string after certain characters?

I have this: /opt/lampp/htdocs/website/inn/hemlata993/93/我有这个: /opt/lampp/htdocs/website/inn/hemlata993/93/

I want to remove /opt/lampp/htdocs and the / at the end so eveyrthing after the 2nd / at the end should get removed.我想删除/opt/lampp/htdocs和最后的/ ,所以最后第二个/之后的所有内容都应该被删除。 In the above example /93 should get removed hence it would be:在上面的示例中/93应该被删除,因此它将是:

/website/inn/hemlata993/

I tried doing this:我试过这样做:

$files = glob($dirName."*.*");
for ($i = 0; $i < count($files); $i++) {
    $image = $files[$i];
    echo $image;
    $arr = explode('/opt/lampp/htdocs', $image);
    $important = $arr[1];
 
    echo '<img src="'.$important.'" width="100" height="100" alt="Random image" />' . "<br /><br />";

}

This removes /opt/lampp/htdocs I was wondering how do I remove the end one as well, and store it in one variable?这将删除/opt/lampp/htdocs我想知道如何删除最后一个,并将其存储在一个变量中? I try using substr, but after removing the first part its storing in array I assume so I am not able to do that.我尝试使用 substr,但在删除第一部分后,我假设它存储在数组中,所以我无法做到这一点。 How can I get /website/inn/hemlata993/ ?我怎样才能得到/website/inn/hemlata993/

One way to achieve this would be to use a regex to match everything after /opt/lampp/htdocs and up to and including the 2nd to last / .实现此目的的一种方法是使用正则表达式匹配/opt/lampp/htdocs之后的所有内容,直到并包括倒数第二个/ For example:例如:

$image = '/opt/lampp/htdocs/website/inn/hemlata993/93/';
$image = preg_replace('#/opt/lampp/htdocs(/.*/)[^/]+/[^/]*$#', '$1', $image);
echo $image;

Output: Output:

/website/inn/hemlata993/

Demo on 3v4l.org 3v4l.org 上的演示

I'd go for a solution that doesn't depend on your website's physical location:我会 go 寻求不依赖于您网站物理位置的解决方案:

$path = '/opt/lampp/htdocs/website/inn/hemlata993/93/';
if (preg_match('#/website/(.*)/(?=\d+/)#', $path, $matches)) {
  $path = $matches[0];
}

This, however, assumes that:然而,这假设:

  • /website is where the files are located within the server's document root, /website是文件位于服务器文档根目录中的位置,
  • the paths always end with one or more digits at the end (before the last / ).路径总是以一个或多个数字结尾(最后一个/之前)。

Demo演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM