How to extract only part of string in PHP?

心不动则不痛 提交于 2019-12-31 03:29:21

问题


I have a following string and I want to extract image123.jpg.

..here_can_be_any_length "and_here_any_length/image123.jpg" and_here_also_any_length

image123 can be any length (newimage123456 etc) and with extension of jpg, jpeg, gif or png.

I assume I need to use preg_match, but I am not really sure and like to know how to code it or if there are any other ways or function I can use.


回答1:


You can use:

if(preg_match('#".*?\/(.*?)"#',$str,$matches)) {
   $filename = $matches[1];
}

Alternatively you can extract the entire path between the double quotes using preg_match and then extract the filename from the path using the function basename:

if(preg_match('#"(.*?)"#',$str,$matches)) {
    $path = $matches[1]; // extract the entire path.
    $filename =  basename ($path); // extract file name from path.
}



回答2:


What about something like this :

$str = '..here_can_be_any_length "and_here_any_length/image123.jpg" and_here_also_any_length';
$m = array();
if (preg_match('#".*?/([^\.]+\.(jpg|jpeg|gif|png))"#', $str, $m)) {
    var_dump($m[1]);
}

Which, here, will give you :

string(12) "image123.jpg" 

I suppose the pattern could be a bit simpler -- you could not check the extension, for instance, and accept any kind of file ; but not sure it would suit your needs.


Basically, here, the pattern :

  • starts with a "
  • takes any number of characters until a / : .*?/
  • then takes any number of characters that are not a . : [^\.]+
  • then checks for a dot : \.
  • then comes the extension -- one of those you decided to allow : (jpg|jpeg|gif|png)
  • and, finally, the end of pattern, another "

And the whole portion of the pattern that corresponds to the filename is surrounded by (), so it's captured -- returned in $m




回答3:


$string = '..here_can_be_any_length "and_here_any_length/image123.jpg" and_here_also_any_length';
$data = explode('"',$string);
$basename = basename($data[1]);


来源:https://stackoverflow.com/questions/2529928/how-to-extract-only-part-of-string-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!