/    Sign up×
Community /Pin to ProfileBookmark

Replacing the First Ocurance of a String

hi,
i want to replace only the first occurance of a String (as u know str_replace() replaces all the occurances of a string)

i want only the first one to be replaced
can u help me???
-ashish

to post a comment
PHP

5 Comments(s)

Copy linkTweet thisAlerts:
@pyroFeb 15.2006 — You could do it like this:

[code=php]<?PHP
$str = 'This is a test. This is also a test.';
$str = preg_replace('/^(.*?)test/i', '$1foo', $str);
echo $str;
?>[/code]
Copy linkTweet thisAlerts:
@ashishrathoreauthorFeb 15.2006 — thanks boss

its working

-ashish
Copy linkTweet thisAlerts:
@ashishrathoreauthorFeb 15.2006 — hey i got into new problem.

this regular expression works well with a string with many words in that

but what i want is a string is there like

"[B]cat2[/B];[email protected];sub[B]cat2[/B]1;#;"

now i want to replace the first one "cat2" and not the other one(the second one in"subcat21")

have got any ideas???

-ashish
Copy linkTweet thisAlerts:
@NogDogFeb 15.2006 — [code=php]
$string = preg_replace('/cat2/', 'foobar', $string, 1); // 4th param limits number of replacements
[/code]

Or, if the string is always formatted that way:
[code=php]
$parts = explode(";", $string);
if($parts[0] == "cat2")
{
$parts[0] == "foobar";
$string = implode(";", $parts);
}
[/code]
Copy linkTweet thisAlerts:
@ashishrathoreauthorFeb 15.2006 — thanks boss again

its working

-ashish
×

Success!

Help @ashishrathore spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.29,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...