使用MYSQL将字母替换为星号,第一个和最后一个字符除外



如何用除第一个和最后一个字符外的星号替换字母例如:house->h***e数据库

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

有一种方法可以在mysql中实现。其他答案可能会给出PHP解决方案,但在mysql:中

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

只需连接第一个字母,然后是星号,最后一个字母。

添加PHP代码以防万一:

// 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();
}

或者,在PHP 7.1或更高版本的中进行替换

// 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();
}

相关内容

最新更新