Page 1 of 1

Regex add character between two strings

Posted: Thu Aug 22, 2013 4:39 am
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!

Re: Regex add character between two strings

Posted: Thu Aug 22, 2013 5:54 am
by Celauran
. matches any character. Try restricting it to a range; [a-Z] or [a-zA-Z]

Re: Regex add character between two strings

Posted: Thu Aug 22, 2013 6:49 am
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 :(

Re: Regex add character between two strings

Posted: Thu Aug 22, 2013 8:03 am
by Celauran
Where are the spaces?

Code: Select all

(={2,6}) ([a-zA-Z]+) (={2,6})

Re: Regex add character between two strings

Posted: Thu Aug 22, 2013 9:58 am
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})/