Regular expression question

Posted on 2006-05-04
Last Modified: 2006-11-18

$str1 = 'some_text_1_' . time() . '_end';
$str2 = 'some_text_103_' . time() . '_end2';

With a regular expression, I want to replace the *value* of time() in $str1 and $str2 with some other string. For example, I want the result as:

$str1 = 'some_text_1_NEW_end';
$str2 = 'some_text_103_NEW2_end2';

Please help.
Question by:karthikramanathan

    Author Comment

    In short, I need a regular expression for this string:



     * denotes a numeric entry,
     # denotes the value of time(), and
     % is some string

    Neither of these symbols can be empty. I want to replace the # with some string. The result should be:

    LVL 29

    Assisted Solution

    How about this:
    $str1 = 'some_text_1_' . time() . '_end';
    $replacement = 'NEW';
    $str1 = preg_replace('/(.*\d+_)(\d+)(.*)/', '$1'.$replacement.'$3', $str1);
    LVL 49

    Accepted Solution

      $str1 = 'some_text_1_' . time() . '_end';
      $str2 = 'some_text_103_' . time() . '_end2';
      $preg = '/(some_text_\d+_)(\d+)(_\w+)/i';
      $repl = 'NEW2';
      echo '<p>'.preg_replace($preg, "\\1$repl\\2", $str1).'</p>';
      echo '<p>'.preg_replace($preg, "\\1$repl\\2", $str2).'</p>';

    Featured Post

    Threat Intelligence Starter Resources

    Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

    Join & Write a Comment

    Consider the following scenario: You are working on a website and make something great - something that lets the server work with information submitted by your users. This could be anything, from a simple guestbook to a e-Money solution. But what…
    Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this.Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is …
    The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
    The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

    746 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    13 Experts available now in Live!

    Get 1:1 Help Now