问题
I need PHP code to replace comma or whitespace with hyphen
For eg:
If $value = 'home garden'
or $value = 'home,garden'
,
i need result as home-garden
I tried $result = preg_replace('/\s+[\,]/', '-', trim($value));
, but no use..
Can someone explain it?
回答1:
$result = preg_replace('/[ ,]+/', '-', trim($value));
Test:
$value = ' home ,garden , gardener ';
$result = preg_replace('/[ ,]+/', '-', trim($value));
echo $result;
//home-garden-gardener
回答2:
$result = str_replace(array(',', ' '), '-', $value);
回答3:
$stringAfter = str_replace(",", "-",$stringBefore);
example:
$stringBefore="abc,def,ghi";
$stringAfter = str_replace(",", "-",$stringBefore);
print $stringAfter;
Output:
`abc-def-ghi`
来源:https://stackoverflow.com/questions/11134495/replace-comma-or-whitespace-with-hyphen-in-same-string