Page 1 of 1

PHP or Regular Expression to match word, and echo it

Posted: Wed Jun 15, 2005 9:44 am
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.

Posted: Wed Jun 15, 2005 10:56 am
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')) {