First 4 Letters of a Variable

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
VKX
Forum Commoner
Posts: 41
Joined: Mon Oct 03, 2005 1:43 pm

First 4 Letters of a Variable

Post by VKX »

How can I set var2 to equal the first four characters of var1?
jmut
Forum Regular
Posts: 945
Joined: Tue Jul 05, 2005 3:54 am
Location: Sofia, Bulgaria
Contact:

Re: First 4 Letters of a Variable

Post by jmut »

VKX wrote:How can I set var2 to equal the first four characters of var1?

Code: Select all

$var2 = substr($var1,0,3);
Is that what you mean?
VKX
Forum Commoner
Posts: 41
Joined: Mon Oct 03, 2005 1:43 pm

Post by VKX »

That's what I was looking for! I was trying preg_match and it wasn't working. Thanks!
jmut
Forum Regular
Posts: 945
Joined: Tue Jul 05, 2005 3:54 am
Location: Sofia, Bulgaria
Contact:

Post by jmut »

VKX wrote:That's what I was looking for! I was trying preg_match and it wasn't working. Thanks!
This should be working with preg_match

Code: Select all

preg_match("%^(.{4})%",$var1,$match);
$var2 = $match[1]; unset($match);
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

preg_match() is overkill for this simple of a need.
Post Reply