Str_replace 1 time

$var="I am a boy";

I have a variabe like the above.

$result=str_replace('a', 'x', $var);

With the code above ,the value of $result will be “I xm x boy”.

I like to make it str_replace the first “a” only.

The would-be code below doesn’t work correctly, but it shows what I want…

$result=str_replace('a', 'x', $var, 1);

My target result is “I xm a boy”

You should be able to that with a combination of strpos and substr_replace.

Or just plain string indexing.
$var[strpos($var,'a')] = 'x';

Yup. That works too for single characters :slightly_smiling_face:

If I apply your code like the below, the result of it is “x”, instead of ““I xm a boy”.

<?php
$var="I am a boy";
echo $var[strpos($var,'a')] = 'x';

You cant echo the assignment statement. Echo $var AFTER the assignment.

Not sure what the point of this is, but it doesn’t require any functions.

<?php
$var="I am a boy";
$var[2] = 'x';
echo $var; // I xm a boy

I think the point is to not have to know in advance where the first letter ‘a’ is found. Your method only works if you have that knowledge to start with.

In this bit,

$result=str_replace('a', 'x', $var, 1);

you’re using a “1” to hopefully control how many replace operations are done, but that’s not what that parameter is for:

1 Like

Yes, in preg_replace that spot is for “limit”. (then there’s a “count”)

Do you know offhand if that creates a global? I’m assuming it does and I suppose an int var polluting globals probably isn’t that much but it would still be something to be aware of.

I think a combination of strpos, substr and str_replace, maybe case insensitive at times, could work - depending.

Seems it shouldn’t be significantly less efficient to just use regex straight away. IMHO this is getting away from what the docs refer to as “simple string replacement”.

1 Like

If you’re asking about the count, I don’t think it is created - you pass in a variable by reference as an optional parameter, and if you don’t pass a pointer (if that’s the right term) to a variable, then it doesn’t return the count. So I would say it depends on how the variable is created before it is passed in. But I don’t know for sure.

1 Like

That is correct; it’s known as an OUT variable. If you pass a variable in, then it will be changed to the number of times the text was replaced. If you don’t pass anything in, nothing happens at all. No global state is changed.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.