我正在尝试编写脚本并解析一个文件,
请帮助在php中使用regex来查找和替换以下模式:
来自:"This is a foo/www/bar.txt is a foo/etc/bar.txt“
致:"This is a bar_txt_content is a bar2_txt_content“
一些类似的东西:
$subject = "This is a foo[/www/bar.txt] within a foo[/etc/bar.txt]";
$pattern = '/regex-needed/';
preg_match($pattern, $subject, $matches);
foreach($matches as $match) {
$subject = str_replace('foo['.$match[0].']', file_get_contents($match[0]), $subject);
}我的第二个要求是:
来自:'This is a foo2bar bar ]‘
致:“这是一个返回的”
一些类似的东西:
$subject = 'This is a foo2[bar bar \] bar bar].';
$pattern = '/regex-needed/';
preg_match($pattern, $subject, $matches);
foreach($matches as $match) {
$subject = str_replace('foo2['.$match[0].']', my_function($match[0]), $subject);
}请帮助构建这些模式...
发布于 2012-08-18 21:44:35
找到转义所需的正确正则表达式:
'/foo\[[^\[]*[^\\\]\]/'发布于 2012-08-18 20:44:14
卢克
这应该会帮助您入门。
http://php.net/manual/en/function.preg-replace.php
您可能需要设置一个循环并增加计数器,使用限制为1的preg_replace仅替换第一个实例。
为了匹配foo/www/bar.txt: regex应该类似于:
foo\[\/www\/([A-Za-z0-9]*)\.txt\]反斜杠用于取消regexp中某些字符的特殊含义。
它将匹配foo[/www/。某些文件name.txt和${1}将包含不带.txt的文件名作为括号形式组,可在替换的表达式中使用。${1}将包含第一轮括号中匹配的内容,${2}将包含第二轮括号中匹配的内容,依此类推...
因此,替换后的表达式应该类似于"${1}_txt_content“。或者在第二次迭代"${1}2_txt_content“中。
A-Za-z0-9*表示任意字母数字字符0次或更多次,如果需要至少1个字符,则可能需要将*替换为+。
所以试试吧:
$pattern = foo\[\/www\/([A-Za-z0-9]*)\.txt\];
$replace = "${1}_txt_content";
$total_count = 1;
do {
echo preg_replace($pattern, $replace, $subject, 1, $count);
$replace = "${1}" + ++$total_count + "_txt_content";
} while ($count != 0);(警告,这是我的第一个PHP程序,所以它可能有错误,因为我不能测试它!但我希望你能明白这一点)
希望这能有所帮助!
托尼
PS:我不是一个PHP程序员,但我知道这在C#中可以工作,例如,看PHP文档,它看起来应该可以工作。
PS2:我总是把这个网站标记为书签,以便在我需要时参考:http://www.regular-expressions.info/
发布于 2012-08-18 20:45:05
如果你总是有一个像foo这样的结构...然后非常简单:
foo\[([^]]+)\]这是.NET语法,但我确信表达式足够简单,您可以进行转换。
正则表达式的描述:
匹配字符“foo”字面上«foo»匹配字符“[”字面«[»匹配下面的正则表达式并将其匹配捕获到反向引用数字1«(^]+)»匹配任何非“]”«^]+»之间的字符,尽可能多次,根据需要(贪婪)«+»匹配字符“]”“字面上«]»
https://stackoverflow.com/questions/12018611
复制相似问题