php - preg_match 所有第一次出现并在文件中获得两个匹配项

标签 php regex

示例字符串:

这是一个包含一些测试用例的示例字符串\cite{author1,author2}。然后是{另一个例子}\citeauthor{author3} 最后是\citeP{author1} 和字符串在这里完成。

要求: 1. 我需要全局提取 {} 之间但在 "\cite"字符串之后的内容。 (例如\cite{..} 或\citeauthor{..})

我试过了: preg_match('/[^\\\\cite]{(.*?)}/', $text, $match);//dint work

2.使用基于分升的提取字符串,字符串将被分解。 (eg. if extracted string="author1,author2") ,则根据","字符进行爆破)
//it will be done with explode()

3.如果大括号来自(\cite or \citeauthor etc) , 它应该替换为 for eg. <xref cite>exploded string</xref>因为我想知道字符串是否来自 "cite" or "citeauthor" or "citeP".

4.如果展开的字符串是第一次出现,我想替换该字符串。 For eg. <xref cite 1>exploded string</xref>

预期输出: 这是带有一些测试用例的示例字符串 <xref cite 1>author1</xref><xref cite 1>author2</xref>.然后{另一个例子} <xref citeauthor 1>author3</xref>最后 <xref citeP>author2</xref>字符串在这里完成。

那么,如何获得(\cite or \citep or \citeauthor)在 {} 之间有一个字符串 以及字符串在文件中的第一次出现。

输出= <xref cite 1>exploded string</xref> - 如果我在 \cite 之后只得到 {} 之间的字符串那我怎样才能得到 "\cite"字符串也与每次出现的那个一样。

谢谢阅读。对不起,大帖子,我认为这是可以理解的

最佳答案

您可以使用 preg_replace_callback :

$s = 'This is a example string with some testing cases \cite{author1,author2}. 
Then {another example} \citeauthor{author3} and finally
\citeP{author1} and string completes here.';

echo preg_replace_callback('/\\\\(cite(?:P|author)?){([^}]*)}/', function($m) {
  return preg_replace('/([^,]+)(?:,|$)/' ,'<xref '. $m[1] . ' 1>$1</xref>', $m[2]); },
  $s);

输出

This is a example string with some testing cases <xref cite 1>author1</xref><xref cite 1>author2</xref>. Then {another example} <xref citeauthor 1>author3</xref> and finally <xref citeP 1>author1</xref> and string completes here.

关于php - preg_match 所有第一次出现并在文件中获得两个匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28293562/

相关文章:

php - 如何获取服务器时间并每秒更新?

php - 如何使用 CodeIgniter 格式化日期

php - 从给定的 id 及其值数组列表中更新特定 id 的特定值

java - 如何批量注释构造函数参数?

php - 如何使用 PHP readfile() 优化资源使用

php - 机器人友好的ajax页面

javascript - 将字符串 ">number<"转换为 "><a href="tel :number">number</a><"

java - java中的ip地址是否有效

javascript - 用于验证具有固定范围的十进制数的正则表达式

php - 未找到类 'MongoDB\BSON\Regex'