Jump to content

detect a space in a variable


jeff5656

Recommended Posts

Let's say I have a variable $x that equals "john smith" and another instance $x equals  "Johnson".

I want to do something like:

 

IF there is a space between 2 words, THEN $newvariable1 = smith and $newvariable2 = John

else: do nothing (i.e. if it's only johnson).

 

How on earth do i do this? :-)

Link to comment
https://forums.phpfreaks.com/topic/245068-detect-a-space-in-a-variable/
Share on other sites

<?php 

$str = 'John Smith Wilson';

if( ($pos = strpos($str,' ')) !== FALSE ) {
// I don't use explode here in case there's 2 or more spaces
$first = substr( $str,0,$pos );
$last = substr( $str,$pos+1 );
echo "'$first' '$last'";
} else
echo $str;

?>

 

If you aren't worried about multiple spaces, then this code will do, keep in mind any spaces beyond 1 will be lost

 

$str = 'John Smith';

if( strpos($str,' ') !== FALSE ) {
list( $first, $last ) = explode( ' ', $str );
echo "'$first' '$last'";
} else
echo $str;

The reason I use !== can be shown in code

 

<?php 

$var = 0;

if( $var == FALSE )
echo 'This will be output';
if( $var === FALSE )
echo 'This will not be output';

?>

 

The function strpos() returns an offset, which can be 0, or FALSE if the string is not found. For example

 

<?php 

$var = 'Hello World';

$test = strpos( $var, 'Hello' );

if( $test == FALSE )
echo 'This will be output, even though the string was found';

if( $test === FALSE )
echo 'This will not be output, because the function returned 0, not exactly FALSE';

?>

 

So, == and != doesn't know the difference between FALSE and 0, or TRUE and a value > 0, while === and !== does.

 

The types of variables compared makes a difference too, when using the EXACT comparison

<?php 

$var = "1";

if( $var == 1 )
echo 'This will be output, even though $var is actually a string';

if( $var === 1 )
echo 'This will not be output, because variable type matters in EXACT comparison';

?>

 

Hope that helps.

If you aren't worried about multiple spaces, then this code will do, keep in mind any spaces beyond 1 will be lost

 

. . .

 

Explode accepts an optional third parameter to specify the maximum number of elements to return:

$str = 'John Smith Wilson';

if( ($pos = strpos($str,' ')) !== FALSE ) {
list( $first, $last ) = explode( ' ', $str , 2 ); // WE ONLY WANT TWO NAME PARTS
echo "'$first' '$last'";
} else
echo $str;

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.