简体   繁体   English

PHP-用星号代替字符,除非有负号

[英]PHP - Replacing characters with stars, except when there is a minus

How can I replace a string with stars except the first and the last letter but not a minus in case there is one . 我如何用星号替换字符串,除了第一个和最后一个字母外,如果有一个,则 不能用减号代替。 Here for better illustration what I try to get: From : url-name To u**-***e 这里是为了更好地说明我尝试获得的内容: 发件人 :url-name u **-*** e

This is what I have so far: 这是我到目前为止的内容:

function get_starred($str) {
        $len = strlen($str);
return substr($str, 0, 1).str_repeat('_', $len - 2).substr($str, $len - 1, 1);
}

You could use the PCRE verbs to skip the first character of a string, last character of a string, and any - s. 您可以使用PCRE动词跳过一个字符串的第一个字符,一个字符串的最后一个字符,以及任何-秒。 Like this: 像这样:

(^.|-|.$)(*SKIP)(*FAIL)|.

https://regex101.com/r/YfrZ8r/1/ https://regex101.com/r/YfrZ8r/1/

PHP example using preg_replace 使用preg_replace PHP示例

preg_replace('/(^.|-|.$)(*SKIP)(*FAIL)|./', '*', 'url-name');

https://3v4l.org/0dSPQ https://3v4l.org/0dSPQ

user3783242 has a great solution - However, if you for some reason do not want to use preg_replace() , you could do the following: user3783242有一个很好的解决方案 -但是,如果由于某种原因不想使用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;

}

hey try implmenting the following: 嘿,尝试实现以下内容:

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;
}

Here is mine: 这是我的:

$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);

This works on multiple words. 这适用于多个单词。

Output 输出量

u**-***e f****r

Sandbox 沙盒

And it also takes into account puctuation 而且它还考虑了操纵

$string = 'url-name foobar.';

Output 输出量

u**-***e f****r.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM