PHP 하위 문자열 추출.첫 번째 '/' 또는 전체 문자열 앞에 문자열을 가져옵니다.
서브스트링을 추출하려고 합니다.PHP로 하는 데 도움이 필요합니다.
다음은 작업 중인 샘플 문자열과 필요한 결과를 보여 줍니다.
home/cat1/subcat2 => home
test/cat2 => test
startpage => startpage
나는 첫 번째까지 끈을 갖고 싶다./
단, 그렇지 않은 경우/
문자열 전체를 가져옵니다.
나는 노력했다.
substr($mystring, 0, strpos($mystring, '/'))
내 생각에 '직책을 받아라'라고 쓰여 있는 것 같아/
서브스트링을 위치 0에서 위치로 이동합니다.
없는 사건을 어떻게 처리해야 할지 모르겠다/
너무 큰 말은 하지 마세요.
PHP 스테이트먼트를 너무 복잡하게 만들지 않고 이 케이스도 처리할 수 있는 방법이 있습니까?
가장 효율적인 솔루션은 다음과 같은 기능입니다.
strtok($mystring, '/')
메모: 여러 글자가 결과에 따라 분할되는 경우, 예를 들어 다음과 같이 기대치를 충족하지 못할 수 있습니다.strtok("somethingtosplit", "to")
돌아온다s
두 번째 인수(이 경우)에서 단일 문자로 분할되기 때문입니다.o
사용되고 있습니다).
@friek108 코멘트로 지적해 주셔서 감사합니다.
예를 들어 다음과 같습니다.
$mystring = 'home/cat1/subcat2/';
$first = strtok($mystring, '/');
echo $first; // home
그리고.
$mystring = 'home';
$first = strtok($mystring, '/');
echo $first; // home
사용
$arr = explode("/", $string, 2);
$first = $arr[0];
이 경우에는,limit
에 대한 파라미터explode
php가 필요 이상으로 문자열을 스캔하지 않도록 합니다.
$first = explode("/", $string)[0];
이건 어때?
substr($mystring.'/', 0, strpos($mystring, '/'))
mystring 끝에 '/'를 추가하면 적어도1개 이상 존재하는지 확인할 수 있습니다.
늦는 것이 안 하는 것보다 낫다.php에는 미리 정의된 함수가 있습니다.여기 좋은 방법이 있습니다.
strstr
일치 전 부품을 가져오려면 before_match(세 번째 파라미터)로 설정합니다.true
http://php.net/manual/en/function.strstr.php
function not_strtok($string, $delimiter)
{
$buffer = strstr($string, $delimiter, true);
if (false === $buffer) {
return $string;
}
return $buffer;
}
var_dump(
not_strtok('st/art/page', '/')
);
승인된 답변의 한 줄 버전:
$out=explode("/", $mystring, 2)[0];
php 5.4+로 동작합니다.
이것이 아마도 내가 생각하는 가장 짧은 예시일 것이다.
list($first) = explode("/", $mystring);
1)list()
다음 시간까지 자동으로 문자열이 할당됩니다."/"
딜리미터를 찾을 수중에 있는 경우
2) 딜리미터의 경우"/"
찾을 수 없는 경우 문자열 전체가 할당됩니다.
...퍼포먼스에 너무 집착하는 경우 폭발적으로 증가하기 위해 추가 파라미터를 추가할 수 있습니다.explode("/", $mystring, 2)
반환되는 요소의 최대 수를 제한합니다.
PHP 5.3의 strstr() 함수가 이 작업을 수행해야 합니다.그러나 세 번째 파라미터는 true로 설정해야 합니다.
그러나 5.3을 사용하지 않는 경우 아래 기능이 정확하게 작동합니다.
function strbstr( $str, $char, $start=0 ){
if ( isset($str[ $start ]) && $str[$start]!=$char ){
return $str[$start].strbstr( $str, $char, $start+1 );
}
}
테스트해 보진 않았지만 잘 될 거예요그리고 꽤 빠르기도 하다.
다음과 같은 정규식을 사용해 볼 수 있습니다.
$s = preg_replace('|/.*$|', '', $s);
regex가 느릴 수 있기 때문에 퍼포먼스가 문제가 되는 경우는 반드시 적절한 벤치마크를 실시해 주십시오.또, 고객에게 적합한 경우는, 다른 대체품을 사용해 주세요.
「」를 사용합니다.current
을 하다.explode
이 과정을 쉽게 할 수 있습니다.
$str = current(explode("/", $str, 2));
이를 처리하기 위해 도우미 기능을 만들 수 있습니다.
/**
* Return string before needle if it exists.
*
* @param string $str
* @param mixed $needle
* @return string
*/
function str_before($str, $needle)
{
$pos = strpos($str, $needle);
return ($pos !== false) ? substr($str, 0, $pos) : $str;
}
다음은 사용 사례입니다.
$sing = 'My name is Luka. I live on the second floor.';
echo str_before($sing, '.'); // My name is Luka
$string="kalion/home/public_html";
$newstring=( stristr($string,"/")==FALSE ) ? $string : substr($string,0,stripos($string,"/"));
사용하지 않는 이유:
function getwhatiwant($s)
{
$delimiter='/';
$x=strstr($s,$delimiter,true);
return ($x?$x:$s);
}
또는:
function getwhatiwant($s)
{
$delimiter='/';
$t=explode($delimiter, $s);
return ($t[1]?$t[0]:$s);
}
언급URL : https://stackoverflow.com/questions/1935918/php-substring-extraction-get-the-string-before-the-first-or-the-whole-strin
'source' 카테고리의 다른 글
내부로 들어가는 방법DOMNode의 HTML? (0) | 2022.10.26 |
---|---|
PHP를 사용하여 MySQL datetime에서 다른 형식으로 변환 (0) | 2022.10.26 |
리터럴 키를 가진 PHP 연결 배열 앞에 추가하시겠습니까? (0) | 2022.10.26 |
모든 텍스트 기반 필드에 범용 varchar(255)를 사용하면 단점이 있습니까? (0) | 2022.10.06 |
Composer가 [Reflection]를 던지다예외] 클래스 Fxp\Composer\자산 플러그인\저장소\npmRepository가 존재하지 않습니다. (0) | 2022.10.06 |