0

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!

3
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by somedude3488
0

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 ) . ' ';
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.