如何在特定字符之前使用preg_match提取字符串中的所有单词

时间:2017-11-03 20:05:05

标签: php regex preg-match pcre

假设我们有以下字符串:

  

Terminator1 Terminator2 Terminator3:Terminator4

给定的正则表达式只能保存Terminator3

var scrollTop = 0;
$(document).ready(function() {
    $(window).on('scroll', function(){
        scrollTop = $(window).scrollTop();
    });

    //use scrollTop here...
});

我必须如何将前3个终结符保存在一个字符串中,因为php的preg_match只能将结果保存为数组?我想用(\w+)(?=:) 作为粘贴所有单词的唯一选择......

示例结果:

implode()

提前致谢

3 个答案:

答案 0 :(得分:1)

$string = "Terminator1 Terminator2 Terminator3: Terminator4";

$result = strtok($string, ":");

echo $result;

答案 1 :(得分:1)

分2步完成,

  1. 匹配<asp:HiddenField runat="server" id="hfID"/> hfID.Value = "Test"; alert($('#hfID').Val());
  2. 在空格上分解结果。
  3. 全部完成!

答案 2 :(得分:1)

我认为我不会使用正则表达式执行此任务(除非您有特殊要求)因为可以使用更快的单功能非正则表达式方法。

代码:(Demo

$input='Terminator1 Terminator2 Terminator3: Terminator4';
//$input='Terminator1 Terminator2 Terminator3 Terminator4'; // no delimiter

echo "strstr: ";
var_export(strstr($input,':',true));  // false when no delimiter is found
echo "\n\n";

echo "strtok: ";
var_export(strtok($input,':'));  // fullstring when no delimiter is found
echo "\n\n";

echo "explode: ";
var_export(explode(':',$input,2)[0]);  // fullstring when no delimiter is found
echo "\n\n";

echo "preg_replace: ";
var_export(preg_replace('/:.*/','',$input));  // fullstring when no delimiter is found
echo "\n\n";

echo "preg_match: ";
var_export(preg_match('/[^:]*/',$input,$out)?$out[0]:'error');  // fullstring when no delimiter is found
echo "\n\n";

echo "preg_split: ";
var_export(preg_split('/:.*/',$input)[0]);  // fullstring when no delimiter is found

输出:

strstr: 'Terminator1 Terminator2 Terminator3'

strtok: 'Terminator1 Terminator2 Terminator3'

explode: 'Terminator1 Terminator2 Terminator3'

preg_replace: 'Terminator1 Terminator2 Terminator3'

preg_match: 'Terminator1 Terminator2 Terminator3'

preg_split: 'Terminator1 Terminator2 Terminator3'