943,925 Members | Top Members by Rank

Ad:
  • PHP Discussion Thread
  • Unsolved
  • Views: 263
  • PHP RSS
Jul 3rd, 2009
0

Regex help

Expand Post »
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...)
PHP Syntax (Toggle Plain Text)
  1. /.{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!
Last edited by Barefootsanders; Jul 3rd, 2009 at 4:35 pm.
Similar Threads
Reputation Points: 10
Solved Threads: 3
Junior Poster
Barefootsanders is offline Offline
165 posts
since Oct 2006
Jul 3rd, 2009
0

Re: Regex help

Post an example string that is to be split, guessing based on your description will produce bad results
Sponsor
Reputation Points: 520
Solved Threads: 268
Code Monkey
ShawnCplus is offline Offline
1,564 posts
since Apr 2005
Jul 3rd, 2009
0

Re: Regex help

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.

PHP Syntax (Toggle Plain Text)
  1. function splitString( $data,$len=50 ) {
  2. $data = explode( ' ',$data );
  3. $result = array();
  4. $i = 0;
  5. foreach( $data as $str ) {
  6. $i = ( $i + strlen( $str ) + 1 );
  7. if ( $i <= ( $len - 1 ) ) {
  8. $result[] = $str;
  9. }
  10. }
  11. return implode( ' ',$result ) . ' ';
  12. }
Reputation Points: 235
Solved Threads: 193
Nearly a Posting Virtuoso
kkeith29 is offline Offline
1,315 posts
since Jun 2007

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in PHP Forum Timeline: T_STRING error (line 183) - NextGen Gallery Plugin
Next Thread in PHP Forum Timeline: Field List Input Problem





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC