繁体   English   中英

用正则表达式替换字符串

[英]Replacing string with regex

我试图从这样的字符串中提取:

$message = #porrabarça per avui @RTorq el  @FCBar guanyarà per 3-1 al AC Milan

'3-1'。 作为数字-数字

我试过了

$message = preg_replace('/[0-9]\s*-\s[0-9]/i', '', $message);

但这是行不通的。 它的输出与输入相同。

你能帮我吗?

问题是\\s在这里。

/[0-9]\s*-\s[0-9]/
           ^
           |
           +--- This makes a single space mandatory. 

您在那里需要\\s* 使用preg_match提取任何内容。 preg_match匹配并且可以选择将匹配设置为变量。 从那里您可以提取匹配项。 preg_replace替换匹配的内容。

preg_match("/\d+\s*-\s*\d+/", $message, $match);
$num = $match[0];

http://ideone.com/BWKZQV

要替换,请使用此模式并将空字符串作为preg_replace替换字符串。

更好的模式是使用POSIX字符类。 它将匹配任何其他语言环境的任何类型数字字符。

/[[:digit:]]+[[:space:]]*-[[:space:]]*[[:digit:]]+/

如果要替换字符串:

<?php  
$message="#porrabarça per avui @RTorq el  @FCBar guanyarà per 3-1 al AC Milan";

echo $message = preg_replace('/[0-9]+-[0-9]+/', '', $message);

?>

如果您想获得匹配的组:

<?php  
$message="#porrabarça per avui @RTorq el  @FCBar guanyarà per 3-1 al AC Milan";

preg_match_all('/[0-9]+-[0-9]+/', $message, $matches);

print_r($matches);

?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM