Hi all.. .I'm trying to use preg_split but I'm having trouble getting the regular expression I want.

What I have now is a long character string, upwards of 200 characters depending on user input. I'm trying to do is break up my string an array, each element in that array having 50 characters. But I dont want to use str_split because that has the possibility to break up the string in the middle of words. So I'd like to create a regular expression that will get at max 50 characters and end in a space and use the functionality of preg_split to accomplish this.

What my pattern looks like is this (and mind you I'm not all that good with regex...)

/.{1,5}(?=\s*)/

Like I said, should be any string 1-50 characters long with a space proceeding the last character.

Any help would be much appreciated.

Thanks!

Post an example string that is to be split, guessing based on your description will produce bad results

I wouldn't use a regular expression for something like this. I am not the best with it and a php function to do it wouldn't be hard.

function splitString( $data,$len=50 ) {
	$data = explode( ' ',$data );
	$result = array();
	$i = 0;
	foreach( $data as $str ) {
		$i = ( $i + strlen( $str ) + 1 );
		if ( $i <= ( $len - 1 ) ) {
			$result[] = $str;
		}
	}
	return implode( ' ',$result ) . ' ';
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.