簡體   English   中英

字符串連續替換三個字符

[英]String Replace Three Characters in a Row

我所擁有的是"text - something else ”,現在可以使用下面的代碼將其轉換為"text-something-else" ,但是我對額外的替換不滿意。

是否有將每一行合並為一行?

PHP:

$url = strtolower(str_replace(" ", "-", splitstring($item->item)));
$url = str_replace("---", "-", $url);

JS:

title = title.toLowerCase().replace(/ /g, '-');
title = title.replace(/---/g, '-');

后者的替換防止了這種情況: "text---something-else" ,所以它們是必需的。

使用正則表達式的功能:

preg_replace('/[ -]+/', '-', $str);

要么:

str.replace(/[ -]+/g, '-');

上面的代碼顯然會用單個連字符替換任何數量的連字符或空格,這與您之前的邏輯略有不同。 如果您希望考慮任何其他字符,則可以輕松執行以下操作:

/[\s_-]+/

上面的內容將匹配任何空格,連字符或下划線。

作為警告,在正則表達式中使用連字符時,應確保它位於[bracketed]組的末尾,即[abc-]否則您將需要使用反斜杠將其轉義,例如[a\\-bc] 這是因為正則表達式語法允許您匹配范圍(例如0-9 ,這在這種情況下將不是您想要的。

試試(我還沒有測試):

// php
$what_to_replace = array(" - ", " ");

// should process " - " first, so spaces around "-" should not be replaced twice
$url = strtolower(str_replace($what_to_replace, "-", splitstring($item->item)));

例子

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM