2016-08-12 2 views
1

가 나는 T 셔츠와 같은 문자열의 끝을 제거 할 문자열 특수 문자로 끝나는 문자열을 제거하는 방법은 무엇입니까?

Clothing, Shoes & Accessories:Men's Clothing:T-Shirts 

같은 있습니다. 내가
end(explode(':',"Clothing, Shoes & Accessories:Men's Clothing:T-Shirts")); 

을 사용하고하지만 난 단지 T 셔츠를

감사

당신이 언급 한 내용에서
+0

정확하게 보존 하시겠습니까? 옷이나 티셔츠 부분? – Jan

답변

2

당신은 간단한 정규식을 사용할 수 있습니다

이 시도 문자열을 채우고 배열에 채워 넣습니다.

end() 함수는 배열의 마지막 요소를 반환하기 때문에 마지막 텍스트 섹션 만 보는 결과가 나타납니다. 실제로하고 싶은 것은 을 제외한 모든 섹션을 얻는 것입니다. 마지막 부분은입니다. 맞습니까?

당신은 당신이에있을 것처럼 보이는 길을 계속하려는 경우, 문자열로 다시 배열을 재결합하여이 작업을 수행하지만, 최종 멤버없이 할 수

:

// Set the string with initial content 
$string = "Clothing, Shoes & Accessories:Men's Clothing:T-Shirts"; 
// Explode the string into an array with 3 elements 
$testArray = explode(':', $string); 
// Make a new array from the old one, leaving off the last element 
$slicedArray = array_slice($testArray, 0, -1); 
// Implode the array back down to a string 
$newString = implode(':', $slicedArray); 

것은 아마 쉬울 것 구분 기호 문자의 마지막 발생을 검색하고 거기에서 문자열의 문자를 제거하지만 유스 케이스에 맞는지 아닌지는 잘 모르겠습니다. 완전성을 위해 다음과 같이 할 수 있습니다.

// Set string with content 
$string = "Clothing, Shoes & Accessories:Men's Clothing:T-Shirts"; 
// Get index of last : character in the string 
$lastIndex = strrpos($string, ':'); 
// Set new string to left portion of original string up til last : char 
$newString = substr($string, 0, $lastIndex); 
2

을 얻고있다

Clothing, Shoes & Accessories:Men's Clothing 

결과가 있어야한다는 폭발 후처럼 보인다 마지막 배열 요소를 제거해야합니다. 이것은 array_pop() 기능이 유용 할 때입니다.

마지막 요소가 제거됩니다. 그런 다음 한 단계 더 시도하고 배열을 파열시킵니다. 짧은 세트로 문자열을 기능이 예상대로 작동) (그래서 당신의 폭발

<?php 
$string = "Clothing, Shoes & Accessories:Men's Clothing:T-Shirts"; 
$regex = '~:[^:]*$~'; 
$string = preg_replace($regex, '', $string); 
echo $string; 
# Clothing, Shoes & Accessories:Men's Clothing 
?> 
0

확인하고, 분할 :

$arr = explode(':', $string); 
array_pop($arr); 
echo implode(':', $arr); // Clothing, Shoes & Accessories:Men's Clothing 
관련 문제