PHP or Regular Expression to match word, and echo it

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
adpd
Forum Newbie
Posts: 9
Joined: Tue Jun 14, 2005 4:37 am

PHP or Regular Expression to match word, and echo it

Post by adpd »

I am trying to find a way of writing in PHP the following:

if $variable is equal to, or begins with "xyz", echo xyz.

The variable is defined as:

Code: Select all

<? $variable = &quote;xyz&quote;; ?>
Some typical examples may be:

<? $variable = "Home"; ?>
<? $variable = "Services"; ?>
<? $variable = "Services Administration"; ?>
<? $variable = "Services Administration Weekly Administration"; ?>
<? $variable = "Services Cleaning"; ?>

The PHP should only match the first word (or words, depending on what is specified), and echo it out.

Thus, from the above example, the first output should be "Home", and the rest should be "Services".

I have had success with the following, but only with an exact match:

Code: Select all

<? if ($variable=="Home") echo "Home"; ?>
<? if ($variable=="Services") echo "Services"; ?>
That example would not work in the case of:

<? $variable = "Services Cleaning"; ?>

The output I would like from the above is "Services", but instead, using the code I currently have, I get no output.

Suggestions or help most welcome.

Thanks

PS - I am new to PHP, so please forgive my ignorance.
User avatar
Skara
Forum Regular
Posts: 703
Joined: Sat Mar 12, 2005 7:13 pm
Location: US

Post by Skara »

Code: Select all

if (preg_match('/^xyz.*/',$string)) {
er.. a faster way would be..

Code: Select all

if (substr($string,0,3) == 'xyz')) {
Post Reply