PHP:检查字符串尾部是否包含数字';破折号';


PHP: Check with a tail of string is contains number after 'dash'

如果尾部包含-1245,我如何剥离下面的字符串?

'product name with color-0250'      -> 'product name with color'
'product name with size-300'        -> 'product name with size'
'product name with something-11200' -> 'product name with something'

我想要的只是产品的名称。

您可以使用explode()并通过'-'进行分解,假定产品名称永远不会包含'-'。

$strProductName = 'product name with color-0250';
$arrParts = explode('-',$strProductName);
echo $arrParts[0]; // Returns: product name with color

您也可以使用带有preg_match或preg_replace的正则表达式。使用preg-replace可以捕获产品名称,即使它包含"-"

echo preg_replace('/('-[0-9]+)$/i', '', 'product name with color-0250');
// Returns: product name with color

preg_replace 的另一个变体

preg_replace("/(.*)-('d+)$/", "$1", "product name with color-0250")

或者您可以使用strrpos():

$str = 'product name with color-0250';
$pos = strrpos($str, '-');       
echo substr($str, 0, $pos); //Returns: product name with color

使用explode()选项。

$test = 'product name with color-0250';
$hi = explode('-',$test);
var_dump($hi[0]); //will give 'product name with color'