I have this PHP code with MySQL database query and I would like to display a record from MySQL database such as first_name
and last_name
records, I would like only to display like PHP echo $row the first 3 letters of the first name and last name output, something like this:
Joh*** Smi***
Jef*** Joh***
$row = "Hamingway";
echo (strlen($row) > 3) ? substr($row, 0, 3) . str_repeat('*', strlen($row) - 3) : str_repeat('*', strlen($row));
And this is the echo output, which works:
Ham******
But this is hand-coded record "Hemingway" and it is not coming from my MySQL Database, I would like something like this display but query and output from my Database records like echo $row['first_name]
and echo['last_name']
2
Answers
You can try this below assume $result is the result of your MySQL query, fetched as an associative array. In this case you would have to adjust the keys accordingly based on your actual database structure.
I am surprised that you weren’t able to swap in your result set variables with the variables in your posted code and you didn’t show how you are iterating your result set, so I guess I’ll spell it all out from the querying step. I want to also show you how to more concisely implement your masking logic in a single function call.
The regex patter will match a character which is followed by zero, one or two characters before the end of the string. Effectively, the last, second last, and third last characters will be replaced — if they exist.
Code: (PHPize Demo with dummy data)
Output from my dummy data: