다음 문자열을 분해하는 가장 좋은 방법은 무엇 다음 속으로PHP 문자열 분해
$str = '/input-180x129.png'
: 당신이해야하는 경우
$array = array(
'name' => 'input',
'width' => 180,
'height' => 129,
'format' => 'png',
);
다음 문자열을 분해하는 가장 좋은 방법은 무엇 다음 속으로PHP 문자열 분해
$str = '/input-180x129.png'
: 당신이해야하는 경우
$array = array(
'name' => 'input',
'width' => 180,
'height' => 129,
'format' => 'png',
);
난 그냥, the string into several variables 및 put them into an array을 분할 preg_split을 사용합니다.
$str = 'path/to/input-180x129.png';
// get info of a path
$pathinfo = pathinfo($str);
$filename = $pathinfo['basename'];
// regex to split on "-", "x" or "."
$format = '/[\-x\.]/';
// put them into variables
list($name, $width, $height, $format) = preg_split($format, $filename);
// put them into an array, if you must
$array = array(
'name' => $name,
'width' => $width,
'height' => $height,
'format' => $format
);
는 Esailija의 위대한 코멘트 후에 내가 더 잘 작동합니다 새로운 코드를 만들었어요!
우리는 단순히 preg_match
에서 모든 일치 항목을 가져오고 이전 코드에서했던 것과 거의 동일합니다.
$str = 'path/to/input-180x129.png';
// get info of a path
$pathinfo = pathinfo($str);
$filename = $pathinfo['basename'];
// regex to match filename
$format = '/(.+?)-([0-9]+)x([0-9]+)\.([a-z]+)/';
// find matches
preg_match($format, $filename, $matches);
// list array to variables
list(, $name, $width, $height, $format) = $matches;
// ^that's on purpose! the first match is the filename entirely
// put into the array
$array = array(
'name' => $name,
'width' => $width,
'height' => $height,
'format' => $format
);
이름에'x'가 있으면 어떨까요? name이'-'을 가질 수없는 한 여전히 모호합니다. 그러나 이것은 실패 할 것입니다. – Esailija
그것에 대해 생각하지 않았습니다! 새 코드 작성 ... -beep beep- –
빠른 응답을 주셔서 감사합니다.하지만 $ str이 /directory/subdirectory/anothersubdirectory/input-180x129.png 인 경우 어떻게해야합니까? 어떻게하면 'input-180x129.png'만 얻을 수 있습니까? –
이 느린 & 바보의 솔루션이 될 수 있습니다,하지만 쉽게 읽을 수 있습니다 : 연관 배열을
$str = substr($str, 1); // /input-180x129.png => input-180x129.png
$tokens = explode('-', $str);
$array = array();
$array['name'] = $tokens[0];
$tokens2 = explode('.', $tokens[1]);
$array['format'] = $tokens2[1];
$tokens3 = explode('x', $tokens2[0]);
$array['width'] = $tokens3[0];
$array['height'] = $tokens3[1];
print_r($array);
// will result:
$array = array(
'name' => 'input',
'width' => 180,
'height' => 129,
'format' => 'png',
);
그냥 알면 읽기가 쉽지 않습니다. 정규 표현식의 기초 그리고 사람이 모르는 경우, 그들은 그것들을 배워야하고, 정규식에 의해 간결하게 표현 될 수있는 것을 표현하기위한 코드 산을 써서는 안됩니다. – Esailija
이 결과 한이되고 있습니까? – BenM
'explode()'에 대해 어떻습니까? – Raptor
현재 코드가 무엇입니까? 어디서 붙어 있니? – Jocelyn