Swap Two Words in a String PHP

swap two words in a string php

Use strtr

From the manual:

If given two arguments, the second should be an array in the form array('from' => 'to', ...). The return value is a string where all the occurrences of the array keys have been replaced by the corresponding values. The longest keys will be tried first. Once a substring has been replaced, its new value will not be searched again.

In this case, the keys and the values may have any length, provided that there is no empty key; additionaly, the length of the return value may differ from that of str. However, this function will be the most efficient when all the keys have the same size.

$a = "foo boo foo boo";
echo "$a\n";
$b = strtr($a, array("foo"=>"boo", "boo"=>"foo"));
echo "$b\n";

Outputs

foo boo foo boo
boo foo boo foo

In Action

How can I swap the values of two different characters in a string with PHP? A becomes B, B becomes A

Just use strtr. It's what it was designed for:

$string = "abcbca";
echo strtr($string, array('a' => 'b', 'b' => 'a'));

Output:

bacacb

The key functionality that helps here is that when strtr is called in the two argument form:

Once a substring has been replaced, its new value will not be searched again.

This is what stops the a that was replaced by b then being replaced by a again.

Demo on 3v4l.org

How to replace multiple items from a text string in PHP?

You can pass arrays as parameters to str_replace(). Check the manual.

// Provides: You should eat pizza, beer, and ice cream every day
$phrase = "You should eat fruits, vegetables, and fiber every day.";
$healthy = ["fruits", "vegetables", "fiber"];
$yummy = ["pizza", "beer", "ice cream"];

$newPhrase = str_replace($healthy, $yummy, $phrase);

PHP - swap the first and third word in a sentence with 3 words

Try this:

$input = "One Two Three";
$words = str_word_count($input, 1);
$reversed_words = array_reverse($words);
print_r($reversed_words); // prints Array ( [0] => Three [1] => Two [2] => One )

Create string:

$input = implode(' ', $reversed_words);
echo $input; // "Three Two One"

How do I swap strings using PHP preg_replace?

I was able to successfully figure it out.

function callback($match)
{
$matchit = strtr($match[0], array('left' => 'right', 'right' => 'left'));
return $matchit;
}

$css= preg_replace_callback('/{(.*?)}/i', 'callback', $css);
echo $css;

The preg_replace_callback is returning anything between { and }. The callback function is replacing left and right.

I am further refining this function to add some kind of ignore trigger so the PHP will ignore certain classes/IDs. Also, it will need to do some reversing on padding and margin, among other things. The entire thing will be made into a class for anyone using PHP to convert CSS to RTL easily.

Update:

You can use this preg_replace instead:

$css = preg_replace_callback('/{(?!\/\*i\*\/)(.*?)}/i', 'callback', $css);

Then you can put /*i*/ into any line you want it to ignore. For example:

.test{/*i*/margin-left:0px;text-align:right}

Replace two words with each other simultaneously

How about using an anonymous function with an array? Any excuse to use an anonymous function, makes me happy :)

$string = "tell me you want to get it right";
$string = implode(" ", array_map(function($word, $swap = ["me", "you"]) {
return ($index = array_search($word, $swap)) === false
? $word : $swap[++$index % 2];
}, explode(" ", $string)));
var_dump($string);
/* string 'tell you me want to get it right' (length=32) */

Or for more complicated replacements

$string = "tell me you want to get it right";
$replacements = ["me" => "you", "you" => "me", "right" => "wrong"];
$string = implode(" ", array_map(function($word) use($replacements) {
return isset($replacements[$word]) ? $replacements[$word] : $word;
}, explode(" ", $string)));
var_dump($string);
/* string 'tell you me want to get it wrong' (length=32) */

How does the XOR trick to swap two variables really work on a string?

PHP applies bitwise operators to strings by applying it to each character individually.

PHP: Bitwise Operators:

Be aware of data type conversions. If both the left-hand and right-hand parameters are strings, the bitwise operator will operate on the characters' ASCII values.

This will work if both strings have the same number of characters, or more precisely the same number of bytes. If the above quote is really precise, then it may only work for ASCII-only strings.

Replacing all words at the same time

strtr() can accept array of pairs 'from' => 'to' to replace as second argument:

echo strtr($string, array('you' => 'me', 'me' => 'you'));

How to replace string in form A_B to string in form B_A?

Using preg_replace:

$input = "hello_world";
$output = preg_replace("/^(.*?)_(.*)$/", "$2_$1", $input);
echo $output;

This approach captures the terms before and after the underscore in two separate groups, and then builds the output by reversing their order. This prints:

world_hello

Here is another approach using explode to generate an array containing both parts of the input:

$input = "hello_world";
$parts = explode("_", $input);
$output = $parts[1] . "_" . $parts[0];
echo $output;

Mix two strings into one longer string PHP

If you want to make a tamper-proof string which is human readable, add a secure hash to it. MD5 is indeed falling out of favour, so try sha1. For example

$salt="secret";
$hash=sha1($string1.$string2.$salt);
$separator="_";
$str=$string1.$separator.$string2.$separator.$hash;

If you want a string which cannot be read by humans, encrypt it - check out the mcrypt extension which offers a variety of options.



Related Topics



Leave a reply



Submit