View Full Version : capturing the first word in a string
james438
12-25-2007, 12:19 AM
How would you go about capturing the first word in a string or variable as a string. For example how would you take
$string = "this is text"; and get the first word out of it so that
$string_first will equal "this"; because "this" is the first word?
Thanks
james438
12-25-2007, 12:48 AM
$text=preg_replace('/\W.*/','',$text);
echo "$text";
works.
$text=preg_split('/[\{.*?\}]/',$text);
echo "$text[0]";
will get the first match of everything between { and } and assign it to the array $text.
$words = explode(' ', $text);
$first_word = $words[0];
$text=preg_split('/[\{.*?\}]/',$text);
echo "$text[0]";If you want to interpolate a complex expression into a double-quoted string you must use braces ({}) to separate it from the rest of the string:
echo "{$text[0]}";However, in both of the examples above the double quotes are merely a waste of resources.
rajug
12-26-2007, 04:45 AM
$words = explode(' ', $text);
$first_word = $words[0];If you want to interpolate a complex expression into a double-quoted string you must use braces ({}) to separate it from the rest of the string:
echo "{$text[0]}";However, in both of the examples above the double quotes are merely a waste of resources.
I would prefer the first one because it is faster than regular expression.
james438
12-27-2007, 10:50 PM
I really need to give better examples when I ask a question. I was creting a program (finished now) where a web designer could enter code into a form to create new style scripts. The form will list the style scripts already in the database so that they can be edited or deleted. Next to each style scrpit is a sample text demonstrating what the CSS would look like when applied to a portion of text.
The script is really only helpful for beginner to intermdiate users and is good as a reference page. I ended up using
$style1=preg_split('/[\{\}]/',$style); to apply that which is within the curly brackets to the sample text.
I have not decided whether to modify it to allow multiple styles to be applied to a single piece of text. For example whether style 1 and style 2 should be applied to "sample text" or whether all of the anchor properties should be applied to a single piece of text. So far it all works fine and I have not run into any problems yet.
Powered by vBulletin® Version 4.2.2 Copyright © 2021 vBulletin Solutions, Inc. All rights reserved.