Add quotes to values in a string separated by a comma in PHP

Posted on

Sometimes we need to add quotes to values in a string separated by comma. For example while using MySQL FULLTEXT search, we need to use some kind of string like ‘pasta’,’ tuna’,’ eggs’ OR finding big list of Ids from MySQL such as WHERE item IN (‘pasta’,’ tuna’,’ eggs’). Here in this post you have running PHP code to add quotes to values in a string separated by a comma using PHP.


<?php
$mystring ="pasta, tuna, eggs";
$result_string = "'" . str_replace(",", "','", $mystring) . "'";
echo "Input String: ".$mystring;
echo “Output String: ".$result_string;
?>

Input String: pasta, tuna, eggs
Output String: ‘pasta’,’ tuna’,’ eggs’

Leave a Reply

Your email address will not be published. Required fields are marked *