如何从以 s
开头并以 /s
结尾的字符串中获取子字符串。
$text
可以采用以下格式
$text = "LowsABC/s";
$text = "sABC/sLow";
$text = "ABC";
怎么能得到ABC
,有时候可能会出现$text
不包含s
而/s
只是ABC
,还是想得到ABC
。
正则表达式:
s(.*)/s
或者,当您想要获取最小长度的字符串时:
s(.*?)/s
并应用您可以使用preg_match
的 res :
preg_match( '@s(.*)/s@', $text, $match );
var_dump( $match );
现在你必须检查,是否发现了什么,如果没有,然后结果必须设置为整个字符串:
if (not $match) {
$match = $text;
}
用法示例:
$ cat 1.php
<?
$text = "LowsABC/s";
preg_match( '@s(.*)/s@', $text, $match );
var_dump( $match );
?>
$ php 1.php
array(2) {
[0]=>
string(6) "sABC/s"
[1]=>
string(3) "ABC"
}
可能微不足道,但是仅仅使用这样的东西呢(正则表达式并不总是值得麻烦;)):
$text = (strpos($text,'s') !== false and strpos($text,'/s') !== false) ? preg_replace('/^.*s(.+)'/s.*$/','$1',$text) : $text;