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];
}

?>

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

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?

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.