Put quotes in the beginning and the end

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
xionhack
Forum Contributor
Posts: 100
Joined: Mon Nov 10, 2008 9:22 pm

Put quotes in the beginning and the end

Post by xionhack »

Hello. I have a string. I want to check if that string has a comma. If it has then to put quotes at the beginning and the end of the string, if it doesnt, then just to save the string.
User avatar
jazz090
Forum Contributor
Posts: 176
Joined: Sun Apr 12, 2009 3:29 pm
Location: England

Re: Put quotes in the beginning and the end

Post by jazz090 »

try this:

Code: Select all

<?php
$string = "a string that has, comma";
if (preg_match("/,/", $string)){
    $string = "\"".$string."\"";
}
echo $string;
?>
outputs:

Code: Select all

"a string that has, comma"
User avatar
php_east
Forum Contributor
Posts: 453
Joined: Sun Feb 22, 2009 1:31 pm
Location: Far Far East.

Re: Put quotes in the beginning and the end

Post by php_east »

i think using strpos is easier and faster.

Code: Select all

<?php
if (strpos(",", $string)) 
{
$string = '"'.$string.'"';
}
echo $string;
?>
Post Reply