Forum Moderators: coopster

Message Too Old, No Replies

preg_replace problem

         

rfontaine

2:56 pm on Sep 22, 2004 (gmt 0)

10+ Year Member



I am making a little content management routine. Here is a problem and I am terrible at regular expressions...

say I have this pattern scattered a number of times througout the text, the "TEXT1" and "TEXT2" not being all the same and can contain such things as numbers, hypens, and spaces etc:

yyyTEXT1¦TEXT2yyy

what I want to end up with is:
yyyTEXT2yyy

In short, get rid of the first word and the "¦" that separates them. How might this be done using preg_replace?

Thank you in advance!

[edited by: rfontaine at 2:59 pm (utc) on Sep. 22, 2004]

rfontaine

2:58 pm on Sep 22, 2004 (gmt 0)

10+ Year Member



anybody?

ergophobe

3:17 pm on Sep 22, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



preg_replace("/(.*?)yyy(.*?)\¦(.*?)yyy(.*)/", "\1yyy\3yyy\4", $input);

Assumptions:
- "yyy" never appears in TEXT2
- you want everything before and after the "yyyTEXT1¦TEXT2yyy"

Note that this forum transforms pipes (¦) so you can't copy and paste this - you must delete and then retype the pipe.

Tom

Guardian

8:37 pm on Sep 23, 2004 (gmt 0)

10+ Year Member



Here is a simpler method

$str = 'yyyTEXT1¦TEXT2yyy';

# if there are not other similar yyyTEXT1¦ patterns
$str = preg_replace('/(yyy)[^¦]+¦/i','$1',$str);

# if there are possibilites of problems
$str = preg_replace('/(yyy)[^¦]+¦(.*?yyy)/i','$1$2',$str);
echo $str; # prints: yyyTEXT2yyy

Have fun
:)

ergophobe

11:38 pm on Sep 23, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I did that twice yesterday - I tested the regex's in something other than PHP where you need to capture everything that you want to be part of the output, not just the parts you need to match.

Anyway, that's a better solution, except that you need to escape the pipe (I'm assuming that it's a pipe and it's the forum software that transformed it into a broken pipe)

echo_pre(preg_replace('/(yyy)[^\¦]+\¦/i','$1',$str));

echo_pre(preg_replace('/(yyy)[^\¦]+\¦(.*?yyy)/i','$1$2',$str));

Thanks Guardian,

Tom

hiker_jjw

11:47 pm on Sep 23, 2004 (gmt 0)



rfontaine,

I've noticed that you've been posting a ton of questions about regular expressions over the past week. I've replied to a couple of them myself.

Now, I'm just too curious. What are you trying to accomplish? Is this some kind of Web data mining? If so, I could suggest an easier way to do things. Just let us know what it is your doing, if it's legal LOL.

Cheers,
Jeff

rfontaine

5:47 pm on Sep 30, 2004 (gmt 0)

10+ Year Member



Well Hiker, I am making a sort of wysiwyg editor. Thank you for your help!

coopster

8:29 pm on Sep 30, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Have you checked out some of the open source options? htmlarea [sourceforge.net], for example?