[英]php regex replace slashes and spaces and hyphens
我需要將幾種字符串組合帶入一種模式,即應刪除多個空格,應將雙連字符替換為單連字符,並將單個空格替換為單個連字符。
我已經嘗試過這種表達方式。
$output = preg_replace( "/[^[:space:]a-z0-9]/e", "", $output );
$output = trim( $output );
$output = preg_replace( '/\s+/', '-', $output );
但這很少會失敗。
我需要幫助使所有這些組合正常工作:
1. steel-black
2. steel- black
3. steel black
我也應該刪除所有這些\\r\\n\\t
。
您可以使用類似這樣的東西(感謝@Robin的更好建議 ):
$s = 'here is a test-- with -- spaces-and hyphens';
$s = preg_replace('/[\s-]+/', '-', $s);
echo $s;
用單個連字符替換任意數量的空格字符或連字符。 您可能還想使用trim($s, '-')
刪除任何前導或尾隨的連字符。 也可以直接在正則表達式中執行此操作,但我認為不這樣做更明顯。
輸出:
here-is-a-test-with-spaces-and-hyphens
如果還有其他要刪除的字符,則可以簡單地將它們添加到方括號表達式中,例如/[()\\s-]+/
也可以刪除括號。 但是,您可能希望只替換所有非單詞字符:
$s = 'here is a test- with -- spaces ( ), hyphens (-), newlines
and tabs ( )';
$s = trim(preg_replace('/[\W]+/', '-', $s), '-');
echo $s;
這會用連字符替換[a-zA-Z0-9_]
以外的任意數量的字符,並刪除所有前導和尾隨連字符。
輸出:
here-is-a-test-with-spaces-hyphens-newlines-and-tabs
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.