Search code examples
phpasp.netregexregular-language

using regular expression for preg replace


i wanna to know the best regular expression to replace this string with the vid_id in it

$code = '&lt;object width=&quot;420&quot; height=&quot;345&quot;&gt;<br />
    &lt;param name=&quot;movie&quot; value=&quot;http://www.badoobook.com/clips/swf/player.swf&quot;&gt;&lt;/param&gt;<br />
    &lt;param name=&quot;allowFullScreen&quot; value=&quot;true&quot;&gt;&lt;/param&gt;&lt;param name=&quot;flashvars&quot; value=&quot;vid_id=100226&amp;MainURL=http%3A%2F%2Fwww.bado  obook.com%2Fclips&amp;em=1&quot;&gt;<br />
    &lt;embed src=&quot;http://www.badoobook.com/clips/swf/player.swf&quot; flashvars=&quot;vid_id=100226&amp;MainURL=http%3A%2F%2Fwww.  badoobook.com%2Fclips&amp;em=1&quot; type=&quot;application/x-shockwave-flash&quot; allowScriptAccess=&quot;always&quot; width=&quot;420&quot; height=&quot;345&quot; allowFullScreen=&quot;true&quot;&gt;&lt;/embed&gt;&lt;/object&gt;'
$regular = '';
$code = preg_replace($regular ,'$1' , $code);
echo $code;

the vid id in this code is

value=&quot;vid_id=100226&amp;

thanks for helping


Solution

  • You could use a Regex like this:

    (?<=vid_id=)\d+
    

    This uses a positive lookbehind to match any number of digits that are preceded by the literal character set "vid_id="

    Here it is again with RegexBuddy comments:

    @"
    (?<=          # Assert that the regex below can be matched, with the match ending at this position (positive lookbehind)
       vid_id=       # Match the characters “vid_id=” literally
    )
    \d            # Match a single digit 0..9
       +             # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
    "
    

    You have tagged your question with both php and asp.net so i'm not sure which implementation you are after. Here is both:

    Asp.Net (C#)

    Regex.Replace(@"...uot;vid_id=100226&amp;...", @"(?<=vid_id=)\d+", "[Your value here]")
    

    php

    echo preg_replace("(?<=vid_id=)\d+", "[Your value here]", "...uot;vid_id=100226&amp;...");