Nicola Cossu
Nicola Cossu

Reputation: 56407

Regular expression to put quotes around each word

Let's suppose I have a string like this

$str = "this is my string";

I need a regular expression in order to have

$str = "'this','is','my','string'";

I know that with this one

preg_match_all("#\w+#",$str,$mth);

I can get an array with single words but I'm not able to reach my goal. Thanks in advance.

Upvotes: 0

Views: 2249

Answers (6)

HITESH PATEL
HITESH PATEL

Reputation: 54

def str = "Fred,Sam,Mike,Sarah"<br/>
str.replaceAll(~"(\\\b)", "'")

This works well in Groovy. (version - 1.8.4)

Upvotes: 0

JohnK813
JohnK813

Reputation: 1124

Do you have to use a regular expression? You can use str_replace to change all the spaces to the sequence ',' then append single quotes at the beginning and end:

$str = "'" . str_replace(" ", "','", $str) . "'";

Upvotes: 2

mellamokb
mellamokb

Reputation: 56779

You can use join / implode to generate the final string.

$str = "'". join("','", $mth). "'";

Or you could just use a direct preg_replace:

$str = "'". preg_replace("#\w+#", "','", $str). "'";

Upvotes: 1

Mike Caron
Mike Caron

Reputation: 14561

$str = "'" . implode("','", explode(' ', $str)) . "'"

No regular expressions needed.

Upvotes: 4

erenon
erenon

Reputation: 19158

If you have the array of words, it's just a simple concat:

$quoted = '';
foreach($words as $word) {
    $quoted .= " '".$word."' ";
}

Upvotes: 1

Morten Kristensen
Morten Kristensen

Reputation: 7623

You could use explode instead:

$parts = explode(" ", $str);

Thus "$parts" will be the array of ["this", "is", "my", "string]. Then you could run through the array and add quotes around each word and finally doing:

$final = implode(",", $parts);

Upvotes: 2

Related Questions