我只想从下面的字符串中得到40,但它可以更改为任何值,如30、5、2、x、yx括号中的字符串是常量,整数是变量除外。所以解决方案是删除以"("开头、以")"结尾的子字符串,并回显其他所有内容?如何做到这一点,我尝试使用子字符串和strpos,但找不到完美的解决方案?这里有人能帮我吗
$string = "40 (In Stock: 1)";
我试过使用
<?php
$stock = "40 (instock: 50)";
$replace_string = substr($stock, strpos($stock, "("), strpos($stock, ")"));
echo str_replace($replace_string,"",$stock);
?>
但还有其他选择吗?
为什么不使用正则表达式?
$string = "40 (In Stock: 1)";
$matches = array();
$pattern = '/('d+) '(.*?')/';
if(preg_match($pattern, $string, $matches))
{
echo $matches[1]; // Prints 40
}