如何用星号替换字符串,除了第一个和最后一个字母,但不能减去负号(如果有的话)。 为了更好地说明,我尝试得到的是: 来自: 网址名称 收件人 u **-*** e
这是我到目前为止所拥有的:
function get_starred($str) {
$len = strlen($str);
return substr($str, 0, 1).str_repeat('_', $len - 2).substr($str, $len - 1, 1);
}
答案 0 :(得分:6)
您可以使用PCRE verbs来跳过字符串的第一个字符,字符串的最后一个字符以及任何-
。像这样:
(^.|-|.$)(*SKIP)(*FAIL)|.
https://regex101.com/r/YfrZ8r/1/
的PHP示例preg_replace('/(^.|-|.$)(*SKIP)(*FAIL)|./', '*', 'url-name');
答案 1 :(得分:2)
user3783242 has a great solution-但是,如果由于某种原因您不想使用preg_replace()
,则可以执行以下操作:
function get_starred($str) {
//make the string an array of letters
$str = str_split($str);
//grab the first letter (This also removes the first letter from the array)
$first = array_shift($str);
//grab the last letter (This also removes the last letter from the array)
$last = array_pop($str);
//loop through leftover letters, replace anything not a dash
//note the `&` sign, this is called a Reference, it means that if the variable is changed in the loop, it will be changed in the original array as well.
foreach($str as &$letter) {
//if letter is not a dash, set it to an astrisk.
if($letter != "-") $letter = "*";
}
//return first letter, followed by an implode of characters, followed by the last letter.
return $first . implode('', $str) . $last;
}
答案 2 :(得分:1)
嘿,尝试实现以下内容:
function get_starred($str) {
$str_array =str_split($str);
foreach($str_array as $key => $char) {
if($key == 0 || $key == count($str_array)-1) continue;
if($char != '-') $str[$key] = '*';
}
return $str;
}
答案 3 :(得分:0)
这是我的:
$string = 'url-name foobar';
function star_replace($string){
return preg_replace_callback('/[-\w]+/i', function($match){
$arr = str_split($match[0]);
$len = count($arr)-1;
for($i=1;$i<$len;$i++) $arr[$i] = $arr[$i] == '-' ? '-' : '*';
return implode($arr);
}, $string);
}
echo star_replace($string);
这适用于多个单词。
输出
u**-***e f****r
它还考虑了操纵性
$string = 'url-name foobar.';
输出
u**-***e f****r.