Re: Re: Substr by words

From: Date: Mon, 31 Oct 2005 03:29:10 +0000
Subject: Re: Re: Substr by words
References: 1 2 3 4 5 6  Groups: php.general 
Request: Send a blank email to php-general+get-224861@lists.php.net to get a copy of this message
Hello, Marcus. Marcus Bointon wrote:
On 30 Oct 2005, at 15:35, Gustavo Narea wrote:
I think that trim($matches[0]) will return the whole string with no change.
No, it will return the entire matching pattern, not just the sub- matches. I added the trim to remove any leading space, and there will nearly always be a trailing space because of the part of my pattern that defines a word will include it. It was simpler to use trim than to make the pattern skip it. Did you actually try it? No. I said that I was not that sure about this because I have not used preg_* functions yet.
On the other hand, I think we have to place a caret after the first slash.
Only if you insist that your string must start with a word - putting a ^ at the start would make it omit the first word if there was a space in front if it. I think It is OK what I said about the caret, but what we need to change is the position of \W*:
Your suggestion: /(\b\w+\b\W*){1,$MaxWords}/ My suggestion: /^(\W*\b\w+\b){1,$MaxWords}/ We need the *first* ($MaxWords)th words.
Instead of preg_match(), I had to type preg_replace():
err. I think you missed the point here. You don't need all that messy substr stuff at all. The preg_match already did it.
Sorry, you are right. Maybe I thought I was talking about the former script I suggested... What do you think if we use the script you suggested, but we change the regex to what I said above? It will look like: <?php $MyOriginalString = "This is my original string.\nWhat do you think about this script?"; $MaxWords = 6; // How many words are needed? $matches = array(); if (preg_match("/^(\W*\b\w+\b){1,$MaxWords}/", $MyOriginalString, $matches)) {
    $result = trim($matches[0]);
    echo $result;
} ?> Best regards, Gustavo Narea.

« previous php.general (#224861) next »