Notes & Code Snippets

Read notes about design & development, or useful scripts and bits of code from me

Return content between delimiters

November 23, 2009

Keywords: php delimiter string

This is an incredibly useful PHP string function for retrieving content between delimiters, such as [bold][/bold]. Useful for parsing BBCode, or for parsing anything in general.
function extract_unit($string, $start, $end){
	$pos = strpos($string, $start);
	$pos2 = strpos($string, $end);
	if( ($pos || $pos == 0) && $pos2 && $pos2 > $pos ){
		$unit = (substr($string, $pos+strlen($start), $pos2-$pos-strlen($start)));
	}
	if( $unit )
		return $unit;
	else
		return false;
}

Back to top

Replace content in a string within delimiters

November 23, 2009

Keywords: str string replace delimit delimiters php

This script replaces content inside delimiters with whatever you want. It's like using str_replace when you only know the beginning and end of the string to be replaced.
function replace_content_inside_delimiters($start, $end, $new, $source) {
	return preg_replace('#('.preg_quote($start).')(.*)('.preg_quote($end).')#si', $new, $source);
}

Back to top