Jump to content

[SOLVED] Extracting specific number of words from text


dpacmittal

Recommended Posts

Mine? I have a working test of it. Albeit simple text, i weren't thinking about punctuation at the time.

 

<?php

$str = 'one two three four five six seven eight nine ten one two three four five six seven eight nine ten one two three four five six seven eight nine ten';

if (preg_match('#([\w]+\s?){0,30}#', $str, $matches))
{
    print $matches[0];
}

?>

Link to comment
Share on other sites

Oh! You're echoing the 0. Hahah, I was using this code

 

<?php

$str = 'one two three four five six seven eight nine ten one two three four five six seven eight nine ten one two three four five six seven eight nine ten';

preg_match('#([\w]+\s?){0,5}#', $str, $matches);

print_r ($matches[1]);


?>

 

It echoed the 1 instead, which is where it stuffed up

Link to comment
Share on other sites

What I did was similar to Mr.Adam's solution.

 

preg_match('!(\s*\S*){1,50}!', $str, $matches);
var_dump($matches);

 

That doesn't actually work. I forget why, but I remember reading that a pattern like that will only match the last word, and after testing it, that holds true

True, but I can always use $matches[0] to get what I needed. I am average at regexes, can you explain your regex?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.