Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/252.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何从较大的字符串中检测具有特定模式的字符串?_Php_Regex_Preg Replace - Fatal编程技术网

Php 如何从较大的字符串中检测具有特定模式的字符串?

Php 如何从较大的字符串中检测具有特定模式的字符串?,php,regex,preg-replace,Php,Regex,Preg Replace,我有一个长字符串,我想从中检测并替换为其他文本。假设我的文本是“我的名字是@[[Rameez]],第二个名字是@[[Rami]]”。我想检测@[[Rameez]]并用Rameez动态替换所有字符串。您可以创建一个正则表达式模式,然后使用它匹配、查找和替换给定字符串。下面是一个例子: string input = "This is text with far too much " + "whitespace."; strin

我有一个长字符串,我想从中检测并替换为其他文本。假设我的文本是
“我的名字是@[[Rameez]],第二个名字是@[[Rami]]”
。我想检测@[[Rameez]]并用Rameez动态替换所有字符串。

您可以创建一个正则表达式模式,然后使用它匹配、查找和替换给定字符串。下面是一个例子:

string input = "This is   text with   far  too   much   " + 
                     "whitespace.";
      string pattern = "\\s+";
      string replacement = " ";
      Regex rgx = new Regex(pattern);
      string result = rgx.Replace(input, replacement);
这是C代码,但实际上你可以将其应用于任何语言。在您的情况下,您可以使用类似于
string pattern=“@[[Rameez]]”的内容替换模式string replacement=“Rameez”
我希望这是有意义的。

您可以简单地执行以下操作:

preg_replace('/@\[\[(\w+)\]\]/', "$1", $string);
[
]
需要转义,因为它们在正则表达式中有特殊含义。
这将用特定版本的
任何字符串替换任何字符串
@[[whatever]]
//专门查找Rameez
$re='/@\[\[(?Rameez)\]\]\]/i';//如果要进行不区分大小写的搜索,请使用i标志
$str='我的名字是@[[Rameez]],第二个名字是@[[Rami].\n我忘了提到我的名字是@[[Rameez]]?';
echo preg__替换($re,$1','**RAMEEZ**(特定)
'.PHP_EOL);
通用版本 正则表达式
@\[\[(?。+?)\]\]
描述

(?…)
在这里表示一个命名的捕获组。有关详细信息,请参阅

示例代码
//查找由@[[和]]括起的任何名称。
$re='/@\[\[(?Rameez)\]\]\]/i';//如果要进行不区分大小写的搜索,请使用i标志
$str='我的名字是@[[Rameez]],第二个名字是@[[Rami].\n我忘了提到我的名字是@[[Rameez]]?';
echo preg_替换($re,$1','**RAMEEZ**(通用)
'.PHP_EOL);

检测
@[[Rameez]]
有什么问题吗?谢谢Stephen。。。。。非常棒的回答,包括完整的解释,特别感谢您让我们了解reg ex tester演示站点。
// Find Rameez specifically
$re = '/@\[\[(?<name>Rameez)\]\]/i'; // Use i flag if you to want a case insensitive search
$str = 'my first name is @[[Rameez]] and second name is @[[Rami]].\nDid I forget to mention that my name is @[[rameez]]?'; 

echo preg_replace($re, '$1', '**RAMEEZ** (specific)<br/>' . PHP_EOL);
@\[\[(?<name>.+?)\]\]
// Find any name enclosed by @[[ and ]].
$re = '/@\[\[(?<name>Rameez)\]\]/i'; // Use i flag if you to want a case insensitive search
$str = 'my first name is @[[Rameez]] and second name is @[[Rami]].\nDid I forget to mention that my name is @[[rameez]]?'; 

echo preg_replace($re, '$1', '**RAMEEZ** (generic)<br/>' . PHP_EOL);