Regex add character between two strings

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

Moderator: General Moderators

Post Reply
radiks
Forum Newbie
Posts: 9
Joined: Thu Aug 22, 2013 4:12 am

Regex add character between two strings

Post by radiks »

Hi,

I have the following string: ====== Text ======. As the number of the = characters may be from 2 to 6 on both sides of the text. I want to insert a dash like this: ====== -Text ======.
For this purpose I use the following code:

Code: Select all

$pattern = "/(={2,6})(.+?)(={2,6})/";
$replace = '$1 -$2$3';
$content = preg_replace($pattern, $replace, $content);
However, when I have some other string like this: ===============================, then a regex add dashes and in it.
I want to add dashes only when there is text between =(equal signs)

Regards!
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Regex add character between two strings

Post by Celauran »

. matches any character. Try restricting it to a range; [a-Z] or [a-zA-Z]
radiks
Forum Newbie
Posts: 9
Joined: Thu Aug 22, 2013 4:12 am

Re: Regex add character between two strings

Post by radiks »

Thanks for the answer!

I did this but does not work: $pattern = '/(={2,6})([a-zA-Z0-9_])(={2,6})/';
I tried and this: $pattern = '/(={2,6})(\w+)(={2,6})/';

But I have no success :(
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Regex add character between two strings

Post by Celauran »

Where are the spaces?

Code: Select all

(={2,6}) ([a-zA-Z]+) (={2,6})
radiks
Forum Newbie
Posts: 9
Joined: Thu Aug 22, 2013 4:12 am

Re: Regex add character between two strings

Post by radiks »

Hi,
Тhanks for the help!
Here's the end result that works:

Code: Select all

/(={2,6}) ([a-zA-Z0-9_ ]+) (={2,6})/
Post Reply