Как получить строку, которая находится внутри двух звездных символов * как StackOverflow - PullRequest
1 голос
/ 13 октября 2011

Как я могу получить строку, которая находится внутри двух звездных символов - * - как здесь StackOverflow?

Например,

$string_1 = 'this is the *string I want to display only*';

или

$string_2 = 'this is the * string I want to display only *'; 

обратите внимание, что во второй строке есть пробелы.

Я хочу вернуть только это,

string I want to display only

Использование регулярных выражений - это то, о чем я могу думать ...есть идеи?

Ответы [ 3 ]

2 голосов
/ 13 октября 2011

Вы можете сделать это с помощью простого регулярного выражения:

Это сохранит все совпадения в переменной matches.

$string = "This string *has more* than one *asterisk group*";
preg_match_all('/\*([^*]+)\*/', $string, $matches);
var_dump($matches[1]);
0 голосов
/ 13 октября 2011

Регулярное выражение решение

$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 String, используя: strpos (), strlen () и substr ()

$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)); 
}
0 голосов
/ 13 октября 2011

Попробуйте это

   $string_1 = 'this is the *string I want to display only*';

    if(preg_match_all('/\*(.*?)\*/',$string_1,$match)) {            
            var_dump($match[1]);            
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...