dsw8292301 2013-03-05 10:24
浏览 73
已采纳

正则表达式 - 如何一次匹配一个模式

I've this function that parses some content to retrieve homemade link tag and convert it to normal link tag.

Possible input:

<p>blabalblahhh <moolinkx pageid="121">text to click</moolinkx> blablabah</p>

Output :

<p>blabalblahhh <a href="whateverpage.htm">text to click</a> blablabah</p>

Here is my code:

$regex = '/\<moolinkx pageid="(.{1,})"\>(.{1,})\<\/moolinkx\>/';
preg_match_all( $regex, $string, $matches );

It works perfectly well if there is only one in the string. But as soon as there is a second one, it doesn't work.

Input:

<p>blabalblahhh <moolinkx pageid="121">text to click</moolinkx>  blablabah.</p>
<p>Another <moolinkx pageid="128">text to clickclick</moolinkx> again blablablah.</p>

That's what I got when I print_r($matches):

Array
(
[0] => Array
    (
        [0] => <moolinkx pageid="121">text to click</moolinkx>  blablabah.</p><p>Another <moolinkx pageid="128">text to clickclick</moolinkx>
    )

[1] => Array
    (
        [0] => 121">text to click</moolinkx>  blablabah.</p><p>Another <moolinkx pageid="128
    )

[2] => Array
    (
        [0] => text to clickclick
    )

)

I'm not at ease with regex, so it must be something very trivial... but I can't pinpoint what it is :(

Thank you very much in advance!

NB: This is my first post here, though I've been using this terrific Q&A for ages!

  • 写回答

2条回答 默认 最新

  • douli0531 2013-03-05 10:55
    关注

    Use a negative Regex:
    $regex = '/<moolinkx pageid="([^"]+)">([^<]+)<\/moolinkx>/';

    Explained demo here: http://regex101.com/r/sI3wK5

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题