I want to add ":" character to all words in string like;
$user = "name, surname, username"
$newString = ":name, :surname, :username"
How can I do that ?
I want to add ":" character to all words in string like;
$user = "name, surname, username"
$newString = ":name, :surname, :username"
How can I do that ?
Yep
$string = preg_replace('/\b(\w)/', ':$1', $string);
Outputs
:name, :surname, :username
Try it online
To explain
\b
- matches a word bondry(\w)
- captures a single a-zA-Z0-9_
Then
:
just adds that in$1
adds the captured char in.Simple, The word boundary means that we capture the first character, then we add the :
and that capture back in.
I would do something like this:
<?php
$user = "name, surname, username";
$array = explode(", ", $user);
$array = array();
foreach ($array as $use) {
$array[] = ":" . $use;
}
$array = implode(", ", $array);
var_dump($array);
?>
The output I get is:
string(26) ":name, :surname, :username"
Try this:
$user = "name, surname, username";
$words = explode(', ', $user);
$newString = implode(', ', array_map(function($i) {return ':' . $i;}, $words));
Assuming ', '
is your delimiter. If not, replace it.
Here is a simple technique using preg_replace which is for regular expressions.
$user = "name, surname, username";
$user = ":" . $user; //appends to beginning of string
$new_string = preg_replace('/, /',',:', $user ); //the pattern can be written better searching for ', '