Skip to content
WJunction - Webmaster Forum

preg_replace first half of matches ?

Status
Not open for further replies.
Hi !
I was wondering if it is possible to replace the first half of matches using only preg_replace ?

Like i have
Code:
[img=some1]
[img=some2]
[img=some3]
[img=some4]

PHP:
$pattern='(\[img=(.*?)\])';
$test=preg_replace($pattern,'replaced',$test);
echo $test;

The above code gives:
Code:
[img=replaced]
[img=replaced]
[img=replaced]
[img=replaced]

RESULT WANTED
Code:
[img=replaced]
[img=replaced]
[img=some3]
[img=some4]

PLS help !
 

1 comment

People should read the manual a little more in depth:

mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )

Meaning you can go:

PHP:
$total_found = preg_match_all('(\[img=.*?\])',$subject);
$test = preg_replace($pattern,'replaced',$test, ceil($total_found / 2));
echo $test;

The 4th param is the limit variable, not to be confused with the 5th param which is count
 
Status
Not open for further replies.

About the author

Porsche_maniak
Established Member · Joined
Auto racing,Porsche,Web Development
283
Messages
0
Reactions
16
Points
Grow your business

Advertise on WJunction

Connect with an established international community of webmasters, hosting providers, developers and online entrepreneurs.

  • Premium & Premium+ Sticky
  • Dedicated section banners
  • Site-wide banner advertising
Explore advertising options
Back
Top Bottom