www.webdeveloper.com
Results 1 to 3 of 3

Thread: preg_replace with incrementing number

  1. #1
    Join Date
    Apr 2010
    Location
    Brooklyn NY
    Posts
    104

    preg_replace with incrementing number

    I have text and a pattern that runs several times. I want it to return an incremented number every time it finds another match. Any ideas?

    Code:
    function return_replace() {
    		static $i = 0;
    		$a = array( '<div><h6 class="toggle" num="' . $i . '">', '</h6>', '<p num="' . $i++ . '">', '</p></div>' );
    		return $a;
    	}
    	
    	function format_toggle_content($content) {
    		$i = 0;
    		
    		$pattern = array( '/<pre><strong>/im', '/<\/strong><\/pre>/im', '/<pre>/im', '/<\/pre>/im' );
    		
    		return preg_replace( $pattern, return_replace(), $content );
    	}

  2. #2
    Join Date
    Jan 2007
    Location
    Wisconsin
    Posts
    2,120
    If you're using PHP >= 5.1, you can use the count parameter:

    Count
    If specified, this variable will be filled with the number of replacements done.
    -- http://php.net/manual/en/function.preg-replace.php

  3. #3
    Join Date
    Apr 2010
    Location
    Brooklyn NY
    Posts
    104
    Learn something new everyday, thanks!

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles