Php 如何获取放置在两个星形符号*内的字符串,如StackOverflow
如何获取放置在两个星号中的字符串,如StackOverflow 比如说,Php 如何获取放置在两个星形符号*内的字符串,如StackOverflow,php,regex,php-5.3,Php,Regex,Php 5.3,如何获取放置在两个星号中的字符串,如StackOverflow 比如说, $string_1 = 'this is the *string I want to display only*'; 或 请注意,第二个字符串上有空格 我只想退这个 string I want to display only 使用正则表达式是我能想到的。。。有什么想法吗?试试这个 $string_1 = 'this is the *string I want to display only*'; if(
$string_1 = 'this is the *string I want to display only*';
或
请注意,第二个字符串上有空格
我只想退这个
string I want to display only
使用正则表达式是我能想到的。。。有什么想法吗?试试这个
$string_1 = 'this is the *string I want to display only*';
if(preg_match_all('/\*(.*?)\*/',$string_1,$match)) {
var_dump($match[1]);
}
正则表达式解决方案
$string_2 = 'this is the * string I want to display only *';
$pattern = "/(\*)+[\s]*[a-zA-Z\s]*[\s]*(\*)+/";
preg_match($pattern, $string_2, $matches);
echo $matches[0];
PHP字符串函数解决方案,使用:strps()、strlen()和substr()
您可以使用简单的正则表达式执行此操作: 这将在变量
matches
中存储所有匹配项
$string = "This string *has more* than one *asterisk group*";
preg_match_all('/\*([^*]+)\*/', $string, $matches);
var_dump($matches[1]);
这有点不够具体。如果字符串包含两个以上的
*
s,您希望发生什么?好问题!我想它应该把整个字符串和星星一起返回,这是StAckOverflow。它在每一页的顶部;我不知道你怎么把它拼错了两次。:)对不起,肯。。。这是一个深夜。。。Lolth这不会像tandu的回答那样有效。字符串hello*craul**world*
将只返回一个结果:craul**world
。
$string = 'this is the * string I want to display only *';
$findme = '*';
$pos = strpos($string, $findme); // get first '*' position
if ($pos !== FALSE) {
// a new partial string starts from $pos to the end of the input string
$part = substr($string,$pos+1,strlen($string));
// a new partial string starts from the beginning of $part to the first occurrence of '*' in $part
echo substr($part,0,strpos($part, $findme));
}
$string = "This string *has more* than one *asterisk group*";
preg_match_all('/\*([^*]+)\*/', $string, $matches);
var_dump($matches[1]);