1

What I'm trying to do is very simple, but I'm looking to do it most efficiently, preferably using php builtin fns.

$str = '1234';
echo replace_function(array('1','3'),array('3','1'),$str);

// output: 3214

str_replace,preg_replace would result in 1214, which means it goes through the arrays, replacing matched strings. I'm looking for a solution to simultaneously "switch" these two (or more) strings.

any ideas?

0

2 Answers 2

6

You need string translate: http://php.net/manual/en/function.strtr.php

<?php
$trans = array("hello" => "hi", "hi" => "hello");
echo strtr("hi all, I said hello", $trans);
// = hello all, I said hi
?> 
Sign up to request clarification or add additional context in comments.

3 Comments

@Sergi, +1, but be sure to credit where you got the example from, and 2, its always nice to give an example that uses the OP's code.
Just watch out for false positives.
I knew there oughtta be something simple like that. Thank you so much!
-2
<?php

$subject = '1234';
$result = preg_replace('/(1)(2)(3)(4)/si', '$3$2$1$4', $subject);
var_dump($result);

?>

You can change the pattern to something more generic, such as '/(\d)(\d)(\d)(\d)/'.

4 Comments

that's not what I'm looking for. I don't know the sequence of the replaced string. Something arbitrary like 3211123 should seamlessly become 1233321.
That will only work on the specific case of '1235' you might as well say $result = '3214' Using '/(\d)(\d)(\d)(\d)/' will change any 4 digits to '3214'
Pity to get "-2" rather than "Thanks". Glad to know strtr().
<?php $subject = "hi all, I said hello"; $result = preg_replace('/(hi)(.+)(hello)/si', '$3$2$1', $subject); var_dump($result); ?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.