Replacing coma with ','?

Hello,
I want regular expression which can replace coma ( , ) with ‘,’ so that
output string can be used in query fetching( using IN in mysql). Anybody having
clue or resources please share!

Regex would be much to inefficient for a simple replace.

The str_replace function is designed for this:

str_replace(',', "','", $text);

But, as you want values enclosed, your full code would be:

<?php
$yourstring = "sport,music,health";
$yourstring = str_replace(',', "','", $yourstring);
$yourstring = "'" . $yourstring . "'";
?>

Now if it’s possible to have a variable number of spaces after the comma, this pattern would cover it.

$str = preg_replace('#,\\s*#', '\\',\\'', $str);

Both arkinstall and joebert, Yoy have given right solution.I understood str_replace function and used previously in my applications. If joebert or someone could please explain me preg_replace regex with specific to my problem of comma replacement. Thanks in advance…!
-Naim

The regex:

#,\\s*#

The #s basically enclose the whole regex string. After it you could put RegEx switches, which could enable multiline matching etc.

You’ll actually find that the most commonly used RegEx encloser is a forward slash, so it may be better for your learning to use it (to stop confusion):

/,\\s*/

Ok, so you can think of the slashes as quotes for the RegEx engine - it only searches for what’s inside them

So, first it looks for a comma (,).
Secondly it looks for 0 or more spaces (\s*) - the \s means a space, the * means it looks for zero or more of them. In other words, spaces are optional and there can be as many as you like.

So, it basically looks for all commas followed by optional spaces, and replaces with a comma inside quotes.

Thank arkinstall! I hope this expaination will help many programmers to understand regex and also this specific solution.Thanks again!

  • Naim
<?php
mysql_connect("localhost","root","root");
mysql_select_db("practise");
$action=$_GET['action'];
$order=$_GET['order'];
$id=$_GET['id'];
if($_POST['submit'])
{
	$color=$_POST['color'];
	$rater=$_POST['rater'];
	$rating=$_POST['rating'];
	if($color=='---')
	{
		$err1='Select Color';
	}
	if($rater=='')
	{
		$err2='Fill up Rater field';
	}
	if($rating=='')
	{
		$err3='Select Rating';
	}
	elseif(!is_numeric($rating))
	{
		$err3='Fill up only numbers ';
	}
	elseif($rating>5)
	{
		$err3='Fill up number less than 6';
	}
	if($_FILES['img']['tmp_name']!='')
	{
		$path='practice/images/';
		move_uploaded_file($_FILES['img']['tmp_name'],$path.$_FILES['img']['name']);
		$img=$_FILES['img']['name'];
		$img_fail=1;
	}
	else
	{
		$img_fail=0;
	}
	if($color!='---' && $rater!='' && $rating!='')
	{
		if($_POST['submit']=='Update')
		{
			$upd_qry="update test set color='$color',rater='$rater',rating=$rating";
			if($img_fail==1)
			{
				$upd_qry.=",img='$img'";
			}
			 $upd_qry.=" where id=$id";
			 mysql_query($upd_qry) or die(mysql_error());
			 header('Location:'.$_SERVER['PHP_SELF']);
			 exit;
		}
		else
		{
			if($img_fail==0)
			{
				$ins_qry="insert into test(color,rater,rating) values('$color','$rater','$rating')";
			}
			else
			{
				$ins_qry="insert into test(color,rater,rating,img) values('$color','$rater','$rating','$img')";
			}
			mysql_query($ins_qry);
			header('Location:'.$_SERVER['PHP_SELF']);
			exit;
		}
	}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>

<body>
<?php
	if(!isset($action))
	{
		echo '<b><font color=red>'.$add_msg.'</b></font><br>';
?>
<a href="testing.php?action=add">Add</a>
<table border="1">
<tr align="center">
<td width="50"><b>Serial No.</b></td><td width="50"><?php if ($order=='CA') { ?><b><a href="testing.php?order=CD">Color</a></b><?php } else { ?><b><a href="testing.php?order=CA">Color</a></b><?php } ?></td><td width="50"><?php if ($order=='UA') { ?><b><a href="testing.php?order=UD">Rater</a></b><?php } else { ?><b><a href="testing.php?order=UA">Rater</a></b><?php } ?></td><td width="50"><?php if ($order=='RA') { ?><b><a href="testing.php?order=RD">Rating</a></b><?php } else { ?><b><a href="testing.php?order=RA">Rating</a></b><?php } ?></td><td width="50"><b>Image</b></td><td width="50"><b>Edit</b></td><td width="50"><b>Delete</b></td>
</tr>
<?php
	if($order=='CD')
	{
		$dspl_qry="select * from test order by color DESC";
	}
	elseif($order=='UD')
	{
		$dspl_qry="select * from test order by rater DESC";
	}
	elseif($order=='RD')
	{
		$dspl_qry="select * from test order by rating DESC";
	}
	elseif($order=='CA')
	{
		$dspl_qry="select * from test order by color ASC";
	}
	elseif($order=='UA')
	{
		$dspl_qry="select * from test order by rater ASC";
	}
	elseif($order=='RA')
	{
		$dspl_qry="select * from test order by rating ASC";
	}
	else
	$dspl_qry="select * from test";
	$res=mysql_query($dspl_qry)or die(mysql_error());
	$serial_no=1;
	while($row=mysql_fetch_assoc($res))
	{
		$path='practice/images/';
?>
<tr align="center">
<td width="50"><?php echo /*$row['id'];*/$serial_no; ?></td><td width="50"><?php echo $row['color']; ?></td><td width="50"><?php echo $row['rater']; ?></td><td width="50"><?php echo $row['rating']; ?></td><td><img src="<?php echo $path.$row['img'] ?>" width="50" height="25" /></td><td width="50"><a href="testing.php?action=edit&id=<?php echo $row['id']; ?>">Edit</a></td><td width="50"><a href="<?php echo $_SERVER['PHP_SELF'].'?action=delete&id='.$row['id']; ?>">Delete</a></td>
</tr>
<?php
	$serial_no++;
	}
?>
</table>
<?php
	$avg_qry="select AVG(rating),color from test group by color";
	$avg_res=mysql_query($avg_qry)or die(mysql_error());
	echo '<table border="1">';
	echo '<tr>';
	while($avg_row=mysql_fetch_assoc($avg_res))
	{
		#$path='practice/images/';
		$avg=round($avg_row['AVG(rating)']);
		$diff_avg=5-$avg;
		echo '<td>';
		echo 'Color=><b>'.$avg_row['color'].'</b>';
		echo '     Average=><b>'.$avg.'</b><br>';
		for($i=0;$i<$avg;$i++)
		{
			echo '<img src='.$path.'staron.jpg />';
		}
		for($j=0;$j<$diff_avg;$j++)
		{
			echo '<img src='.$path.'staroff.jpg />';
		}
		echo '<br>';
		echo '</td>';
	}
	echo '</tr>';
	echo '</table>';
	}	
?>

<?php
	if(isset($action))
	{
		if($action=='delete')
		{
			$path='practice/images/';
			$res=mysql_query("select img from test where id=$id");
			$row=mysql_fetch_assoc($res);
			$img=$row['img'];
			#echo $img;
			mysql_query("delete from test where id=$id");
			if($img!='')
			{
				unlink($path.$img);
			}
			header('Location:'.$_SERVER['PHP_SELF']);
			exit;
		}
		if($action=='edit')
		{
			$edt_qry="select * from test where id='$id'";
			$edt_res=mysql_query($edt_qry) or die(mysql_error());
			if(mysql_num_rows($edt_res)!=0)
			{
				$edt_row=mysql_fetch_assoc($edt_res);
				$color=$edt_row['color'];
				$rater=$edt_row['rater'];
				$rating=$edt_row['rating'];
			}
			else
			{
				header('Location:'.$_SERVER['PHP_SELF']);
				exit;
			}	
		}
		if($action=='edit'|| isset($id))
		{
			$post_action=$_SERVER['PHP_SELF'].'?action=add&id='.$id;
			$submit_val='Update';
		}
		else
		{
			$post_action=$_SERVER['PHP_SELF'].'?action=add';
			$submit_val='Add';
		}
?>
<a href="testing.php">Summery</a>
<table>
<form method="post" action="<?php echo $post_action; ?>" enctype="multipart/form-data" />
<tr>
<td>
<strong>Color:</strong>
<select name="color">
<option value="---" selected>---</option>
<option value="blue" <?php if($color=='blue'){?> selected <?php } ?>>Blue</option>
<option value="black" <?php if($color=='black'){?> selected <?php } ?>>Black</option>
</select>
</td>
<td><?php echo $err1; ?></td>
</tr>
<tr>
<td>
<strong>User:</strong>
<input type="text" name="rater" value="<?php echo $rater; ?>" />
</td>
<td><?php echo $err2; ?></td>
</tr>
<tr>
<td>
<strong>Rating given:</strong>
<b>1</b><input type="radio" name="rating" value="1" <?php if($rating==1) {?> checked <?php } ?> />
<b>2</b><input type="radio" name="rating" value="2" <?php if($rating==2) {?> checked <?php } ?> />
<b>3</b><input type="radio" name="rating" value="3" <?php if($rating==3) {?> checked <?php } ?> />
<b>4</b><input type="radio" name="rating" value="4" <?php if($rating==4) {?> checked <?php } ?> />
<b>5</b><input type="radio" name="rating" value="5" <?php if($rating==5) {?> checked <?php } ?> />
</td>
<td><?php echo $err3; ?></td>
</tr>
<tr>
<td>
<strong>Choose Image:</strong>
<input type="file" name="img" />
</td>
<td><?php echo $err4; ?></td>
</tr>
<tr>
<td>
<input type="submit" name="submit" value="<?php echo $submit_val; ?>" />
</td>
</tr>
</form>
</table>
<?php
	}
?>
</body>
</html>
<?php
session_start();
mysql_connect('localhost','root','root');
mysql_select_db('practise');
$action=$_GET['action'];
$id=$_GET['id'];
if($_POST['submit'])
{
	$item=$_POST['item'];
	$desc=$_POST['description'];
	if($item=='' || $desc=='')
	{
		echo 'Please Fill up Relevent Fields';
	}
	elseif($item!='' || $desc!='')
	{
		if($_POST['submit']=='Update')
		{
			$upd_qry="update aed set item='$item',description='$desc' where id=$id";
			mysql_query($upd_qry) or die(mysql_query());
			$_SESSION['msg']='Data <b>Updated</b> Successfully!';
			header('Location:aed.php');
			exit;
		}
		else
		{
			$ins_qry="insert into aed(item,description) values('$item','$desc')";
			mysql_query($ins_qry) or die(mysql_query());
			$_SESSION['msg']='Data <b>Added</b> Successfully!';
			header('Location:aed.php');
			exit;
		}
	}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Add Edit Update Delete Operations in a Single Form</title>
<script type="text/javascript">
function delconfirm(id)
{
	var conf=confirm('Are you Sure?');
	if(conf)
	{
		location.href='aed.php?action=delete&id='+id;
	}
	else
	{
		return false;
	}
}
</script>
</head>

<body>
<?php
if(!isset($action))
{
echo $_SESSION['msg'];
?>
<br>
<a href="aed.php?action=add">Add</a>
<table border="1">
<tr>
<td><strong>Item</strong></td><td><strong>Description</strong></td><td><strong>Edit</strong></td><td><strong>Delete</strong></td>
</tr>
<?php
	$show_qry="select * from aed";
	$show_res=mysql_query($show_qry) or die(mysql_error());
	while($show_row=mysql_fetch_array($show_res))
	{
 ?>
<tr>
<td><?php echo $show_row['item']; ?></td><td><?php echo $show_row['description']; ?></td><td><a href="aed.php?action=edit&id=<?php echo $show_row['id']; ?>">Edit</a></td><td><a style="cursor:pointer" onclick="return delconfirm(<?php echo $show_row['id'] ?>);">Delete</a></td>
</tr>
<?php
	}
?>
</table>
<?php
}
if(isset($action))
{
	if($action=='delete')
	{
		$del_qry="delete from aed where id=$id";
		mysql_query($del_qry);
		$_SESSION['msg']='Row <b>Deleted</b> Successfully!';
		header('Location:aed.php');
		exit;
	}
	if($action=='edit')
	{
		$edt_qry="select * from aed where id=$id";
		$edt_res=mysql_query($edt_qry) or die(mysql_error());
		$edt_row=mysql_fetch_array($edt_res);
		$item=$edt_row['item'];
		$desc=$edt_row['description'];
	}
	if($action=='edit' || isset($id))
	{
		$post_action=$_SERVER['PHP_SELF'].'?action=add&id='.$id;
		$submit_value='Update';
	}
	else
	{
		$post_action=$_SERVER['PHP_SELF'].'?action=add';
		$submit_value='Add';
	}
?>
<br><a href="aed.php">Report</a>
<form method="post" action="<?php echo $post_action; ?>">
<table>
<tr>
<td>
<strong>Item:</strong>
</td>
<td>
<input type="text" name="item" value="<?php echo $item; ?>" />
</td>
<tr>
<td>
<strong>Description:</strong>
</td>
<td>
<textarea name="description" rows="3" cols="25"><?php echo $desc; ?></textarea>
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" name="submit" value="<?php echo $submit_value; ?>" />
</td>
</tr>
</table>
</form>
<?php
}
unset($_SESSION['msg']);
?>
</body>
</html>