Asked  7 Months ago    Answers:  5   Viewed   39 times

How can I replace a certain part of my string with another one?

Input string:

"Hello, my name is Santa"

How can I change all a's in my string with something else?

I think I need a foreach loop, but I'm unsure how to use it.


strtr ($str, array ('a' => '<replacement>'));

Or to answer your question more precisely:

strtr ("Hello, my name is Santa", array ('a' => '<replacement>'));
Wednesday, March 31, 2021
answered 7 Months ago

Not tested, but probably something like if(preg_match("/^[0-9,]+$/", $a)) $a = str_replace(...)

Wednesday, March 31, 2021
answered 7 Months ago

I don't think you can do this using any of the search and replace functions, so you'll have to code up the replace yourself.

It looks to me like this problem works well with explode(). So, using the example token generator you provided, the solution looks like this:

$shrapnel = explode('%%token%%', $str);
$newStr = '';
for ($i = 0; $i < count($shrapnel); ++$i)  {
    // The last piece of the string has no token after it, so we special-case it
    if ($i == count($shrapnel) - 1)
        $newStr .= $shrapnel[$i];
        $newStr .= $shrapnel[$i] . rand(100,10000);
Wednesday, March 31, 2021
answered 7 Months ago

The bug is in str.replace(start_pos, end_pos, to);

From the std::string doc at

string& replace ( size_t pos1, size_t n1,   const string& str );

You are using an end-position, while the function expects a length.

So change to:

while((start_pos = str.find(from, start_pos)) != std::string::npos) {
         str.replace(start_pos, from.length(), to);
         start_pos += to.length(); // ...

Note: untested.

Sunday, June 13, 2021
answered 5 Months ago

You don't even need to use substring or replace, you can use this:

SELECT 'test' + RIGHT(email, charindex('@', REVERSE(email)))
FROM YourTable

You can test it out with this:

DECLARE @email nvarchar(50)
SET @email = ''
PRINT 'test' + RIGHT(@email, charindex('@', REVERSE(@email)))
Thursday, August 12, 2021
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :