Ho fatto due funzioni, perchè non riuscivo a fare il tutto con un'unica espressione regolare.
Dovrebbero funzionare praticamente in tutti i casi, fai qualche prova e fammi sapere.
Codice PHP:
/* se il testo ha meno di n parole torna il testo per intero */
function firstwords($text, $n) {
return preg_match('/^([^a-z]*[a-z]+){'.$n.'}/i', $text, $matches) ? $matches[0] : $text;
}
/* se il testo ha meno di n parole torna il testo per intero */
function lastwords($text, $n) {
return preg_match('/([a-z]+[^a-z]*){'.$n.'}$/i', $text, $matches) ? $matches[0] : $text;
}
$text = "Ciao come stai, io sono l'ultima parola";
var_dump(firstwords($text, 4));
var_dump(lastwords($text, 4));
Ciao