Simple regex help

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
andy1989
Forum Newbie
Posts: 8
Joined: Sat Sep 24, 2011 12:36 pm

Simple regex help

Post by andy1989 »

Hey everyone,

I'm a real noob at regex I need to replace patterns of this text:

style/synth-pop-d14

style/guitar-rock-d43

genre/rock-metal-d20

etc.

I need to replace it .. so If anyone could give me the right Regex for search and replace purposes it would be great!

Thanks a lot :)
User avatar
twinedev
Forum Regular
Posts: 984
Joined: Tue Sep 28, 2010 11:41 am
Location: Columbus, Ohio

Re: Simple regex help

Post by twinedev »

Well, what part of it are you wanting to replace, or anything in a string that looks similar to that.

Will it always be just like that:
1. lower case letters
2. forward slash
3. lower case letters
4. hyphen
5. lower case letters
6. hyphen
7. combination lower case letters and/or numbers

Do you need to capture any of that back into a variable to use?

-Greg
andy1989
Forum Newbie
Posts: 8
Joined: Sat Sep 24, 2011 12:36 pm

Re: Simple regex help

Post by andy1989 »

It's always the same yes :)
I just need it for a replacing job..
I tried something like: ^[a-z]+/[a-z]+-[a-z]+-[a-z0-9]

but what is the right code?>
User avatar
twinedev
Forum Regular
Posts: 984
Joined: Tue Sep 28, 2010 11:41 am
Location: Columbus, Ohio

Re: Simple regex help

Post by twinedev »

Code: Select all

$strVariable = preg_replace('%^[a-z]+/[a-z]+-[a-z]+-[a-z0-9]+$%i','REPLACEMENT_TEXT',$strVariable);
andy1989
Forum Newbie
Posts: 8
Joined: Sat Sep 24, 2011 12:36 pm

Re: Simple regex help

Post by andy1989 »

OK thanks man but it detects everything but the last part

I mean: style/guitar-rock instead of style/guitar-rock-d43
there is a problem with the [a-z0-9] part
User avatar
twinedev
Forum Regular
Posts: 984
Joined: Tue Sep 28, 2010 11:41 am
Location: Columbus, Ohio

Re: Simple regex help

Post by twinedev »

Just tested it on my server, ran the following code:

Code: Select all

<?php

$strVariable = 'style/guitar-rock-d43';

echo "Start Value: $strVariable \n";

$strVariable = preg_replace('%^[a-z]+/[a-z]+-[a-z]+-[a-z0-9]+$%i','REPLACEMENT_TEXT',$strVariable);

echo "End Value: $strVariable \n"; ?>
And got this:[text]Start Value: style/guitar-rock-d43
End Value: REPLACEMENT_TEXT[/text]

-Greg
ozzybee
Forum Newbie
Posts: 1
Joined: Wed Nov 02, 2011 10:11 am

Re: Simple regex help

Post by ozzybee »

Can anyone help me with my own regex question?

I am trying to ensure data in a text field always matches this pattern

jsmith,T10,IT Manager
jyard,T09,Sales Director

so basically
[a-z],[a-z 0-9],[a-z ]\n
[a-z],[a-z 0-9],[a-z ]\n

any number of times.

Any ideas?
Post Reply