简体   繁体   中英

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

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. Like this:

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

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

PHP example using preg_replace

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

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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