提取以破折号结尾的变量的一部分"-"



我有一个变量$TYPE=K180M-2

我需要"在新变量中仅提取直到破折号 (K180M) 的部分。

我该怎么做?

你可以试试:

$arr=explode("-", $TYPE);

$arr[0]会给你想要的结果。

<?php
$newType = substr($TYPE, 0, stripos($TYPE, '-'));
?>

会工作。

您可以使用explode

<?php
$K180M = '45';
$TYPE = 'K180M-2';
$var = explode('-',$TYPE,2);
$$var[0]; // this is your new variable named $K180M
var_dump($$var[0]); // result 45

如果您更喜欢正则表达式,请使用 preg_replace()

// Delete the dash and anything following it:
$type_without_dash = preg_replace("/-.*/", "", $TYPE);

只需使用
$value=strstr($TYPE,'-',TRUE);

最新更新