0

How can I Replace letters with asterisks except first and last character for example: house -> h***e Database

<div id="ld">    
        <?php
    $base=mysqli_connect('localhost','root','','exercise');
    $request="select text from exercise";
       /*
       Here I want to show all words from database but with letters replaced
       with asterisks (expect first and last letter)
      */
    mysqli_close($base)
        ?>
  </div>
Garr Godfrey
  • 8,257
  • 2
  • 25
  • 23

1 Answers1

0

There is a way to do it in mysql. Other answers may give PHP solution, but in mysql:

SELECT CONCAT(LEFT(text,1), REPEAT('*',LENGTH(text)-2), RIGHT(text,1)) AS text FROM exercise

simply concatenate the first letter, then your asterisks, then last letter.

Adding the PHP code just in case:

// New Connection
$db = new mysqli('localhost','user','pass','database');


$result = $db->query("SELECT CONCAT(LEFT(text,1), REPEAT('*',LENGTH(text)-2), RIGHT(text,1)) AS text FROM exercise");
if($result){
    // Cycle through results
    while ($row = $result->fetch_object()){
        echo $row;
    }
    // Free result set
    $result->close();
}

alternatively, doing the replacement in PHP 7.1 or later

// New Connection
$db = new mysqli('localhost','user','pass','database');


$result = $db->query("SELECT text FROM exercise");
if($result){
    // Cycle through results
    while ($row = $result->fetch_object()){
        if (strlen($row) > 2) {
           echo  $row[0] . str_repeat('*', strlen($row)-2) . $row[-1]
        }
        else {
           echo $row
        }

    }
    // Free result set
    $result->close();
}
Garr Godfrey
  • 8,257
  • 2
  • 25
  • 23
  • What happens if the word is one letter long? What happens if the word is two letters long? – mickmackusa Dec 15 '21 at 13:20
  • @mickmackusa in the PHP version, it leaves the original unaltered. In the mysql version, works fine for 2 character string or zero length string. For a 1 character string, it will double it, so 'a' becomes 'aa' – Garr Godfrey Dec 15 '21 at 19:05