使用PHP从字符串中检索一段单词


Retrieve piece of words from string using PHP

我有一个这样的字符串:

$mystring = '[5][1][0]One[4][0][0]Two[8][1][1]Three';

如何获得这些:

$prefix1 = '[5][1][0]';
$prefix2 = '[4][0][0]';
$prefix3 = '[8][1][1]';
$newString = 'One Two Three';

以下是使用Regex提取所需结果的两个示例。这可以优化为一个表达式。但这应该是你的一个起点:

获取:"One Two Three"

preg_match_all("/']([a-z]*)/i", $a, $m);
print implode(' ', array_filter($m[1])) . "'n";

获取:"[5][1][0]""[4][0][0]""[8][1][1]"

preg_match_all("/('[[0-9'[']]*)[a-z]/i", $a, $m);
foreach($m[1] as $v) {
    print $v . "'n";    
}

进一步阅读

  • 正则表达式
  • 填充图案修改器
  • preg_match_all