/    Sign up×
Community /Pin to ProfileBookmark

Replacing the 1st occurence in a string

i should know this one but don’t.

given a string …

$str = “hello my name is bob.”

how would i replace only the first space character
with some default text $default = “###”;

so $str would become “hello###my name is bob.”

i tried str_replace but it seems it will always replace all occurences


to post a comment

6 Comments(s)

Copy linkTweet thisAlerts:
@NogDogNov 19.2008 — preg_replace() has a limit parameter you could use.
$text = preg_replace('/ /', '###', $text, 1);
Copy linkTweet thisAlerts:
@bsmbahamasauthorNov 19.2008 — thanks nogdog, you're always rescuing me.

much appreciated.
Copy linkTweet thisAlerts:
@bsmbahamasauthorNov 19.2008 — would it be difficult to have php perform a google search, and then parse the results and return only the amount of results google found?

for example a search for coffee mugs returns 6,220,000.

i just want the results not the listings.
Copy linkTweet thisAlerts:
@SyCoNov 20.2008 — Well this works but only for sure as of today. You'd have to keep an eye on the format of the HTML surrounding the result, if it changes you're out of luck. Maybe there's an API solution but for a straight up cURL and parse, it'll get a number. I imagine someone can improve upon it?


$searchterms='whatever you want';

$url = "http://www.google.com/search?q=".urlencode($searchterms);
$ch = curl_init(); // initialize curl handle
curl_setopt($ch, CURLOPT_URL,$url); // set url to post to
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);// allow redirects
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // return into a variable
curl_setopt($ch, CURLOPT_TIMEOUT, 10); // times out after 10s
$result = curl_exec($ch); // run the whole process

$pattern="/of about .*> for </";
$temp=str_replace('of about <b>','',$matches[0]);
$num=str_replace('</b> for <','',$temp);
echo $num;

?> [/code]
Copy linkTweet thisAlerts:
@bsmbahamasauthorNov 20.2008 — thanks that works perfectly, i'll have to do some research into that curl function
Copy linkTweet thisAlerts:
@SyCoNov 20.2008 — cURL is a really neat tool. Remember this is a fairly fragile way to do things but, hey it works (for now) ?


Help @bsmbahamas 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 3.3,
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: @darkwebsites540,
tipped: article
amount: 10 SATS,

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

tipper: Anonymous,
tipped: article
amount: 10 SATS,