Forum Moderators: coopster

Message Too Old, No Replies

Trim everything but the last word from a sentence

by using php

         

jake66

7:54 am on Jun 26, 2008 (gmt 0)

10+ Year Member



The Mysql result for $result['name'] is Big Blue Widget

How can I make this just say "widget"?

Presently, I use:

if (strpos($result['name'],'Widget')){
echo'Widget';
}

about 20 different times.. I imagine this is not very efficient.

milocold

9:17 am on Jun 26, 2008 (gmt 0)

10+ Year Member



Hi Jake66,

You can use regular expressions to grab the last word of a sentence:

<?php

$str = 'MiloCold is Neat';
$str_Pattern = '/[^ ]*$/';

preg_match($str_Pattern, $str, $results);

// Prints "Neat", but you can just assign it to a variable.
print $results[0];

?>

Hope that helps,

M. Cold

jake66

9:20 am on Jun 26, 2008 (gmt 0)

10+ Year Member



Awesome. That does exactly what I needed, thanks!

bedlam

9:43 am on Jun 26, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Another method below. Whichever method you use, you might want to do something about any punctuation that might show up at the beginning and end of the final word.


<?php
function lastWord($sentence) {
// Break the sentence into its component words:
$words = explode(' ', $sentence);
// Get the last word and trim any punctuation:
$result = trim($words[count($words) - 1], '.?![](){}*');
// Return a result:
return $result;
}
$string = "Lorem ipsum dolor sit amet consectetuer.";
echo lastWord($string);
?>

Returns:

consectetuer

Good reading on string manipulation (plus links to the various regex functions) here [php.net].

-- b

jake66

9:52 am on Jun 26, 2008 (gmt 0)

10+ Year Member



Thanks for the link.
The query isn't going to have any punctuation (the field doesn't allow it)

Which method is faster / less server-intensive?

eelixduppy

7:29 am on Jun 27, 2008 (gmt 0)



>> Which method is faster / less server-intensive?

Hard to say. Run a few tests to find out. microtime() is pretty good for something like this, actually. Read the documentation for more information. For something like this, however, it's not likely that there will be much of a difference.

milocold

7:40 am on Jun 27, 2008 (gmt 0)

10+ Year Member



I dunno which method would run faster, but for readability purposes I would most likely use bedlam's method. The explode function is much more convenient than using a regular expressions.

Those regexp patterns give me gray hair! Nice thinkin' bedlam! =)

Thinks back to KISS,

M. Cold

eelixduppy

7:52 am on Jun 27, 2008 (gmt 0)



Without testing, I'd imagine this method would be fastest given the tasks the code actually does:

$string = 'Here is a sentence';
$last_word = [url=http://www.php.net/substr]substr[/url]($string, [url=http://www.php.net/strrpos]strrpos[/url]($string, ' '));