从两个特定字符之间的字符串中间获取短语

问题描述 投票:0回答:4

我想提取字符串中两点之间的字符串部分。

我的输入字符串是

{you: awesome; feeling good}

我想使用 PHP 获取

feeling good
;
之间的单词
}

php string substring text-extraction
4个回答
3
投票
$arr = explode(';', trim("{you: awesome; feeling good}", '{}'));
$feel_good_string = trim($arr[1]);
echo $feel_good_string;

0
投票

其他选择是......

$str = "{you: awesome; feeling good}";
$str = trim($str,"{}");
echo substr($str,strpos($str,";")+1);

0
投票

您可以在 PHP 中使用

explode()
来分割字符串。

示例1:

$string = '{you: awesome; feeling good}'; // your string
preg_match('/{(.*?)}/', $string, $match); // match inside the {}
$exploded = explode(";",$match[1]); // explode with ;
echo $exploded[1]; // feeling good

示例2:

$string = '{you: awesome; feeling good}'; // your string
$exploded = explode(";", $string);  // explode with ;
echo rtrim($exploded[1],"}"); // rtrim to remove ending } 

0
投票

通过使用正则表达式模式,您可以避免生成临时数组或执行单独的提取和清理步骤。

代码:(演示

$string = "{you: awesome; feeling good}";
echo preg_replace('/[^;]*; ([^}]*).*/', '$1', $string);
// feeling good

模式与整个字符串匹配。

开始匹配零个或多个非分号字符,然后是一个空格。 然后捕获零个或多个非右括号字符。 然后匹配字符串的其余部分。 用捕获的中间段替换完整字符串。

© www.soinside.com 2019 - 2024. All rights reserved.