[Tutorial] Implode with a regular expression

Example of PHP code.

Moderator: Moderators

[Tutorial] Implode with a regular expression

Postby Phantom on Sat Nov 05, 2005 4:21 pm

For those that utilize the regular expression feature of preg_split(), you'll find that there is no available function to implode the array with the same regex. Therefore, I have recently made a small function that will act as a regex form of implode().

Code: Select all

* Join string by a regular expression.
* @author      Joshua Rennert <admin@jphantom.com>
* @version     1.0.1
* @param       string     $glue        Regular expression
* @param       string     $text        Original text
* @param       array      $array       Array pieces
* @return      string
function preg_join ( $glue, $text, $array )
   preg_match_all ( addslashes ( $glue ), $text, $paste );

   for ( $i = 0; $i < count ( $array ); $i++ )
      $copy .= $array[$i] . $paste[0][$i];
   $join = $copy;
   return $copy;


So say you want to make the word 'upload' bold, but don't want it to interefere with a URL that has the word 'upload' in it (ex: http://yoursite.com/upload.php).

You would first split your text:
Code: Select all
$cut = preg_split ( '/<a href="(.*?)">/', $your_text );

Next, you would run a loop and bold the word 'upload':
Code: Select all
for ( $i = 0; $i < count ( $cut ); $i++ )
   $cut[$i] = preg_replace ( '/upload/i', '<b>upload</b>', $cut[$i] );

Finally, since there is no real function in PHP that can implode an array with regex, you can utilize the small function I created above:
Code: Select all
$highlighted_text = preg_join (  '/upload/i', $your_text, $cut );

Hope this helps you in some fashion. Happy coding.

// Phantom
"Best of the best of the best, sir! With honors!" -- MIB
[ jphantom.com ]
Registered User
Registered User
Posts: 245
Joined: Mon Apr 18, 2005 3:24 am

Return to PHP Tutorials

Who is online

Users browsing this forum: No registered users and 1 guest