개발! 딱 깔끔하고 센스있게!

PHP 에서 문자열 을 slug 으로 변환 합 니 다. 본문

개발 스크랩 메모/PHP

PHP 에서 문자열 을 slug 으로 변환 합 니 다.

렉사이 2020. 12. 3. 02:40

한 줄 의 텍스트 를 단락 으로 바 꾸 는 가장 좋 은 방법 은 무엇 입 니까?의미:

  • alpha allowed, convert to lowercase
  • numbers are allowed
  • spaces should be eliminated, not converted to dash ("-")
  • accented characters replaced by equivalent standard alpha
  • no other characters allowed, should be stripped out

나 는 인터넷 에서 많은 코드 를 찾 았 지만, 모두 빈 칸 을 디 폴 트 사이즈 로 바 꾸 는 경향 이 있어 서, 나 는 이렇게 하고 싶 지 않다.

나 도 전환 에 관심 이 있다.

그 중:

  • ampersand ("&") should be replaced by the string "and"

그리고 변형, 그 중:

  • Don't bother converting accented characters to equivalent standard alpha

대답 하 다.

이것 은 내 가 최초 로 여기에서 찾 은 수 정 된 함수 (http: / cubiq. org / the perfect. php clean url generator) 입 니 다.

'-' 를 구분자 로 전달 할 수 있 습 니 다.

public static function createSlug($str, $delimiter = '-'){ $slug = strtolower(trim(preg_replace('/[\s-]+/', $delimiter, preg_replace('/[^A-Za-z0-9-]+/', $delimiter, preg_replace('/[&]/', 'and', preg_replace('/[\']/', '', iconv('UTF-8', 'ASCII//TRANSLIT', $str))))), $delimiter)); return $slug; } 
Comments