如何显示以某个字符开头并以php中的cetain字符结尾的字符串的一部分?

时间:2016-07-19 10:22:48

标签: php

我想从下面的字符串中只获得40但它可以更改为任何值,如30,5,2,x,y x括号中的字符串是常量,除了作为变量的整数。所以解决方案是删除以“(”开头并以“)”开头的子串,并回显其他所有内容?如何做到这一点,我尝试使用子串和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);
?>

但还有其他选择吗?

1 个答案:

答案 0 :(得分:3)

为什么不使用正则表达式?

$string = "40 (In Stock: 1)";
$matches = array();
$pattern = '/(\d+) \(.*?\)/';
if(preg_match($pattern, $string, $matches))
{
     echo $matches[1]; // Prints 40
}