Ask Your Question

How do you make use of regex within a variable?

asked 2013-01-24 11:16:07 -0600

Luke gravatar image

updated 2013-02-27 09:12:17 -0600

llowder gravatar image

For example.

Lets say I have a generated variable that looks like this:

$mytext = 1a2b3c4d

I want a way to take just the first 6 characters and use it as another variable

$mytest2 = first 6 characters of $mytext

So something like? /^\w\w\w\w\w\w/

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2013-01-24 13:23:49 -0600

llowder gravatar image

updated 2013-01-24 14:58:49 -0600

You should be able to use the regsubst() function.

$mytest2 = regsubst($mytest, '^(.{6}).*$', '\1')
edit flag offensive delete link more



you have to put the replacement in quotes thought. So for example $mytest2 = regsubst($mytest, '^(.{6}).*$', '\1')

Stefan gravatar imageStefan ( 2013-01-24 14:22:14 -0600 )edit

Hi Guys. Thanks for the help. I tried running both examples the top one gave me an error because I didn't have the \1 in quotes and the second ...(more)

Luke gravatar imageLuke ( 2013-01-24 14:49:08 -0600 )edit

Sorry checked my syntax again I forgot the { } you had around the 6. Stefan's example worked perfect. Thanks guys!

Luke gravatar imageLuke ( 2013-01-24 14:51:33 -0600 )edit

I hadn't tested my answer, was basing it off a quick read of the docs. I'll update it to include the proper example.

llowder gravatar imagellowder ( 2013-01-24 14:58:08 -0600 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools


Asked: 2013-01-24 11:16:07 -0600

Seen: 549 times

Last updated: Jan 24 '13