0

I want to add ":" character to all words in string like;

$user = "name, surname, username"

$newString = ":name, :surname, :username"

How can I do that ?

4 Answers4

1

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.

ArtisticPhoenix
  • 21,464
  • 2
  • 24
  • 38
  • Thank you for reply, I need to start learn about regex.. Do you have any suggest for doc or video tutorial ? –  Apr 08 '18 at 00:09
  • 1
    Not really but this site that the tester is on https://regex101.com/r/VrJJhQ/1/ has a lot of help stuff on the lower right. – ArtisticPhoenix Apr 08 '18 at 00:10
  • @HasanTıngır you might want to read this documentation, it is quite a steep learning curve but the end results will be worth the effort for sure: http://php.net/manual/en/reference.pcre.pattern.syntax.php – Paul G Mihai Apr 08 '18 at 01:11
0

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"
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
0

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.

0

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 ', '
mcv
  • 1,380
  • 3
  • 16
  • 41