我有一个看起来像这样的变量:
$var1 = "33081PA-5112";
有时它变成:
$var1 = "33083";
$var1 = "33081PA-1132";
$var1 = "31183";
$var1 = "13081PA-2132";
我如何确定它何时具有 PA-,所以当它确实时,我想将 PA- 之后的数值放入其他变量中。
谢谢
使用 strpos():
if(strpos($var,'PA-') !== false) // code to run if the string has a PA-
干得好:
<?php
$var1 = "13081PA-2132";
$pos = strpos( $var1, 'PA-');
echo $pos . "\n";
if( $pos > -1 )
{
$newVal = substr($var1, $pos+3 );
echo $newVal;
}
?>
输出:
5
2132
这会给你你想要的。
$var1 = "33081PA-1132";
preg_match('/^([0-9]*)PA-/',$var1,$match);
$var1_cut = $match[1];
preg_match('/PA-([0-9]*)/',$var1,$match);
$var2 = $match[1];
//Outputs
print_r($var1); //33081PA-1132
print_r($var1_cut); //33081
print_r($var2); //1132
你可以做一个regex
匹配:
preg_match("{PA-(\d+)}",$var,$array);
echo $array[1][0];
<?php
$var1 = "33083";
$var1 = "33081PA-1132";
if(strstr($var1, 'PA') !== false){ // If it has the PA
$parts = explode('PA-', $var1); // Split by dash
echo $parts[0]; // Left part
echo '<br />';
echo $parts[1]; // Right part
}else{
echo $var1; // It has not PA
}
?>
if(trim(str_replace(range(0,9),'', $var1)) == 'PA-') {
//do stuff
}