Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

EbrahemSamer's avatar

How to replace part of string with * and show the rest ( PHP ) ?

I am searching using the name , I want the result of search to be like that

if i searched for any person start with 'ahmed' the result would be like that

ahmed ********* ahmed *** ahmed*

and so on just ahmed appears and the rest will be hidden like that how can i do that ?

0 likes
1 reply
ahmeddabak's avatar
Level 47

You need to use regex for that

$query = "Ahmed"; //what you are querying in the db

$string = "Ahmed is the user name"; //the result you got from the database

$regex = "/\b(?!{$query}\b)\w+/"; //add the query to your regular expression

$result =  preg_replace($regex,'*',$string);

var_dump($result); // Ahmed * * * *

Please or to participate in this conversation.