2010-03-13 6 views
1

내 문자열의 쓸데없는 부분을 제거하는 방법을 찾을 수 없습니다. (SQL에서 읽음) strreplace를 시도했지만 잘리지 않았습니다. 조금도.PHP 문자열 조작 ("_"및 타임 스탬프 지우기)

나는 내가 그것을 후 _와 문자를 지우려면

145_timestamp = $ 물건 경우 $ 물건라는 문자열 변수를 가지고있다. 그래서 $ 물건은 145 일뿐입니다. 감사.

+0

그래, 그 초보자 질문을 알고 있지만, 단순히 PHP 매뉴얼에서 해결책을 찾을 수 없습니다. 링크로 충분합니다. –

답변

3

try explode 문자열을 구분 기호에 따라 배열로 분할합니다. 당신은 구분 기호로 _를 사용하는 경우, 당신은 current를 사용하여 배열에서 첫 번째 값을 선택할 수 있습니다 :

$number = current(explode("_", $stuff)); 
+1

이것은 가장 비효율적 인 방법입니다 - 폭발은 값 배열을 만드는 모든 노력으로 이어지지 만 사용되지 않습니다. 그것은 muurugaperumal의 int 캐스트 제안보다 10 배 느립니다. –

+0

조기 최적화 등등 ... : – Marius

1
$string = preg_replace("/_[^_]+$/",'',$string); 
+0

'_'가 여러 개이면? – Gumbo

3
$stuff = "145_timestamp"; 
$stuff=(int)$stuff; 
print $stuff; 
+0

참고 : $ stuff = "020_timestamp"인 경우 20이됩니다. 이것은 020과 동일한 것일 수도 있고 그렇지 않을 수도 있습니다. – Piskvor

0

intval 문자열의 정수 값을 가져옵니다. 아니면 정규 표현식을 사용하거나 폭발 할 수 : 나는 내 자신의 몇 가지 제안을 추가, 여기에 제안 된 다양한 방법을 통해 몇 가지 벤치 마크를 실행

$int = preg_replace('/^(\d+)/', '$1', $string); 
$int = explode('_', $string)[0]; 
4

을 - 다음은 각 방법 100000 반복의 타이밍은

int cast  : 79.45ms 
intval  : 394.39ms 
strtok  : 428.85ms 
preg_replace : 604.68ms 
substr  : 719.92ms 
explode  : 821.99ms 

int 캐스팅 방법은 1 마일 정도이기는하지만 앞에서 설명한 것처럼 맨 앞자리 0을 제거합니다. Intval은 동일한 결과를 얻는 속도가 느린 방법입니다.

과 함께 사용하는 빠른 방법은 strtok ($ str, '_');을 사용하는 것입니다.

$str="154_timestamp"; 
$c=100000; 

$s=microtime(true); 
for ($x=0; $x<$c; $x++) 
    $n=(int)$str; 
printf("int cast : %0.2fms\n", (microtime(true)-$s)*1000); 

$s=microtime(true); 
for ($x=0; $x<$c; $x++) 
    $n = current(explode("_", $str)); 
printf("explode : %0.2fms\n", (microtime(true)-$s)*1000); 

$s=microtime(true); 
for ($x=0; $x<$c; $x++) 
    $n = substr($str, 0, strpos($str, '_')); 
printf("substr : %0.2fms\n", (microtime(true)-$s)*1000); 

$s=microtime(true); 
for ($x=0; $x<$c; $x++) 
    $n = strtok($str, '_'); 
printf("strtok : %0.2fms\n", (microtime(true)-$s)*1000); 

$s=microtime(true); 
for ($x=0; $x<$c; $x++) 
    $n = intval($str); 
printf("intval : %0.2fms\n", (microtime(true)-$s)*1000); 

$s=microtime(true); 
for ($x=0; $x<$c; $x++) 
    $n = preg_replace("/_[^_]+$/",'',$str); 
printf("preg_replace : %0.2fms\n", (microtime(true)-$s)*1000); 
+0

@ Paul Dixon : 좋은 물건들. SQL에서 바꾸기/캐스팅을 수행하는 것은 어떻습니까? – middus