Change one of the array value if it equals to something - php

I'm using explode() php function to divide the sentence and turn it into array the user had filled in the input field on different page. From that sentence I need to find if there is that word and if it is in it add <b></b> around of that word. I've tried:
$wordsentence = explode(' ', $wordsentence);
$place == '0';
foreach ($wordsentence as $ws) {
if ($ws == $word) {
$word = '<b>'.$word.'</b>';
$save = $place;
}
$place++;
}
but there might be more than one word in the same sentence. Is there any way to mark multiple words?

You initial setup:
$wordSentence = "This is a sentence, made up of words";
$wordTest = "made";
$wordsArr = explode(' ', $wordSentence);
I swapped out the foreach loop for a standard for loop, this way we don't need to initialize a separate index variable and keep track of it.
for ($i = 0; $i < count($wordsArr); $i++) {
if ($wordsArr[$i] == $wordTest) {
$boldWord = '<b>' . $wordTest . '</b>';
//take your wordsArray, at the current index,
//swap out the old version with the bold version
array_splice($wordsArr, $i, 1, $boldWord);
}
}
And to complete our test:
$boldedSentence = implode(' ', $wordsArr);
echo $boldedSentence . "\n";
Output:
> This is a sentence, <b>made</b> up of words

Related

how to get first two word from a sentence using php for loop

I am trying to get first two word from a sentence using php
$inp_val= "this is our country";
output will be : this is
// this input value has different string as Like: this, this is our, this name is mine
// i need to get only first two word or if anyone wrote only one word then i got same word but if any one wrote two or more word then it will collect only first two word..
I am trying with below code but it won't work properly..
$words = explode(' ', $inp_val);
$shop_name = "";
if (str_word_count($words) == 1) {
$shop_name .= mb_substr($words[0], 0, 1);
} else {
for ($i = 0; $i < 2; $i++) {
$w = $words[$i];
$shop_name .= mb_substr($w, 0, 1);
}
}
After exploding the input value by space (as you have done), you can use array_slice to extract the 2 first elements, then use the implode to concat the 2 elements as a string.
$inp_val = "this is our country";
$shop_name = implode(" ", array_slice(explode(' ', $inp_val), 0, 2));
echo $shop_name;
//OUTPUT: this is
This method that uses array_slice work well for one or more words

How to filter propertly or how to explode specific string

Sorry to bother but I have tried now everything -.-
(INPUT STRING)
kronobergslan_Preem_AlmhultS_Esplanaden__diesel
this is the string, first value after _ is separate, second value after _ is separate, every other values except the last after __ is together as separate value.
so basically I want to make this:
(EXPECTED OUTPUT)
$a = kronobergslan
$b = Preem
$c = Almult S Esplanden
$d = diesel
Example 2:
(INPUT STRING)
kronobergslan_Circle_K_VaxjoSodra_Vallviksvagen_352_51_Vaxjo__diesel
(EXPECTED OUTPUT)
$a = kronobergslan
$b = Circle K
$c = Vaxjo Sodra Vallviksvagen 35251 Vaxjo
$d = diesel
I have tried everything.
public function filter($call){
// kronobergslan_Circle_K_VaxjoEvedalsvagen__diesel to Kronobergslan CircleK (Vaxjo Evedalsvagen)
// kronobergslan_Ingo_VaxjoSmedjegatan_28__Morners_vag__diesel to Kronobergslan Ingo (Vaxjo Smedjegatan 28 Morners vag)
// return array
$parts = explode("_", $call);
$parts = array_map('ucfirst', $parts);
// if part 2 and 3 is cirlek make one string
if($parts[1] == "Circle"){
$parts[1] = $parts[1] . " " . $parts[2];
unset($parts[3]);
}
$parts[10] = ucfirst(substr($call, strpos($call, "__") + 2));
//= $parts[count($parts) - 1];
if ($parts[2] != "K"){
$part = preg_split('/(?=[A-Z])/',$parts[2]);
$parts[2] = implode(' ', $part);
$parts[2] = $parts[2] . " " . $parts[3];
unset($parts[3]);
}else if ($parts[2] == "K"){
$parts[2] = "test";
}
return $parts;
}
Would be thankful if someone could explain how to approach this problem and how to solve it so I would learn from it and probably be able to solve it other times.
You're presented with a few problems with your expected input strings.
#kronobergslan_Preem_AlmhultS_Esplanaden__diesel
$parts = explode('_', $call);
#Outputs:
#kronobergslan
#Preem
#AlmhultS
#Esplanaden
#[empty entry]
#diesel
I would suggest, replace every space with another custom boundary, that way in the example of AlmhultS_Esplanaden you can still separate the input string with a simple explode and not have it be confused in these instances. Once separated, you can replace the _ with a \s.
I'm not sure why the last value has a double-underscore __ but since it's there, you can still use explode and then just remove the 2nd last value in the returned array using the unset method.
$parts = explode('_', $call);
$count = count($parts);
for ($i = 0; $i < $count; $i++) {
$parts[$i] = preg_replace('/','/\s/');
}
unset($parts[$count]-1);
As a side note, never use " unless you're concatenating a string. Always use ' single quotes.

How to display specific letters from a list of words in a loop?

I received this challenge in an interview and I would like some help solving it.
Using the input string: PHP CODING TECH, produce the following output.
PCT
PHCT
PHPCT
PHPCOT
PHPCODT
PHPCODIT
PHPCODINT
PHPCODINGT
PHPCODINGTE
PHPCODINGTEC
PHPCODINGTECH
As I understand it, the logic is to explode the input string on the spaces and then in a loop structure, display the leading letter(s) of each word as a single string. During each iteration (after the first), the earliest incomplete word displays an additional leading letter.
This is my coding attempt:
$str = "PHP CODING TECH";
$a = explode(' ', $str);
for ($i=0; $i < count($a); $i++) {
for ($j=0; $j < strlen($a[$i]) ; $j++) {
//echo "<pre>";
$b[$i][$j] = explode(' ', $a[$i][$j]);
}
}
echo "<pre>";
print_r($b);
Code: (Demo) (or with DO-WHILE())
$input = "PHP CODING TECH";
$counters = array_fill_keys(explode(' ', $input), 1); // ['PHP' => 1, 'CODING' => 1, 'TECH' => 1]
$bump = false; // permit outer loop to run
while (!$bump) { // while still letters to output....
$bump = true; // stop after this iteration unless more letters to output
foreach ($counters as $word => &$len) { // $len is mod-by-ref for incrementing
echo substr($word, 0, $len); // echo letters using $len
if ($bump && isset($word[$len])) { // if no $len has been incremented during inner loop...
++$len; // increment this word's $len
$bump = false; // permit outer loop to run again
}
}
echo "\n"; // separate outputs
}
Output:
PCT
PHCT
PHPCT
PHPCOT
PHPCODT
PHPCODIT
PHPCODINT
PHPCODINGT
PHPCODINGTE
PHPCODINGTEC
PHPCODINGTECH
Explanation:
I am generating an array of words and initial lengths from the exploded input string. $bump is dual-purpose; it not only controls the outer loop, it also dictates the word which gets a length increase within the inner loop. $len is "modifiable by reference" so that any given word's $len value can be incremented and stored for use in the next iteration. isset() is used on $word[$len] to determine if the current word has more available letters to output in the next iteration; if not, the next word gets a chance (until all words are fully displayed).
And while I was waiting for this page to be reopened, I whacked together an alternative method:
$input = "PHP CODING TECH";
$words = explode(' ', $input); // generates: ['PHP', 'CODING', 'TECH']
$master = ''; // initialize for first offset and then concatenation
foreach ($words as $word) {
$offsets[] = strlen($master); // after loop, $offsets = [0, 3, 9]
$master .= $word; // after loop, $master = 'PHPCODINGTECH'
}
$master_offsets = range(0, strlen($master)); // generates: [0,1,2,3,4,5,6,7,8,9,10,11,12]
do {
foreach ($offsets as $offset) {
echo $master[$offset];
}
echo "\n";
} while ($master_offsets !== ($offsets = array_intersect($master_offsets, array_merge($offsets, [current(array_diff($master_offsets, $offsets))])))); // add first different offset from $master_offsets to $offsets until they are identical

Search through array and removing duplicates

I am trying to remove duplicates from a text field. The text field auto suggests inputs and the user is only allowed to choose from them.
The user however has the option of choosing same input field more than once. It's an input fields that states the firstname + lastname of each individual from a database.
First, this is my code to trim some of the unwated characters and then going through the array comparing it to previous inputs.
if(!empty($_POST['textarea'])){
$text = $_POST['textarea'];
$text= ltrim ($text,'[');
$text= rtrim ($text,']');
$toReplace = ('"');
$replaceWith = ('');
$output = str_replace ($toReplace,$replaceWith,$text);
$noOfCommas = substr_count($output, ",");
echo $output.'<br>';
$tempArray = (explode(",",$output));
$finalArray[0] = $tempArray[0];
$i=0;
$j=0;
$foundMatch=0;
for ($i; $i<$noOfCommas; $i++) {
$maxJ = count($finalArray);
for ($j; $j<$maxJ; $j++) {
if ($tempArray[$i] === $finalArray[$j]) {
$foundMatch ===1;
}
}
if ($foundMatch === 0) {
array_push($finalArray[$j],$tempArray[$i]);
}
}
What is it am I doing wrong ?
In this part when checking if the values are equal:
if ($tempArray[$i] === $finalArray[$j]) {
$foundMatch ===1;
}
It should be:
if ($tempArray[$i] === $finalArray[$j]) {
$foundMatch = 1;
}
That way you are setting the variable and not checking if it's equal to 1. You can also break the inner for loop when finding the first match.
I think that this should work:
if (!empty($_POST['textarea'])){
$words = explode(',',str_replace('"', '', trim($_POST['textarea'], ' \t\n\r\0\x0B[]'));
array_walk($words, 'trim');
foreach ($words as $pos=>$word){
$temp = $words;
unset($temp[$pos]);
if (in_array($word, $temp))
unset($words[$pos]);
}
}
echo implode("\n", $words);
First it reads all the words from textarea, removes '"' and then trim. After that it creates a list of words(explode) followed by a trim for every word.
Then it checks every word from the list to see if it exists in that array (except for that pos). If it exists then it will remove it (unset).

Assign variable to values in array php

This is what I want to do:
Split a word into separate charachters. The input word comes from a form and can differ from each user.
Assign variables to each charachter so that i can manipulate them separately.
Her's my code so far (which doesn't work). Apoligize if ther's a lot of stupid mistakes here, but I am new to PHP.
<?php
$word = $_POST['input'];
//split word into charachters
$arr1 = str_split($word);
//assigning a variable to each charchter
$bokstaver = array();
while($row = $arr1)
{
$bokstaver[] = $row[];
}
$int_count = count($bokstaver);
$i=0;
foreach ($bokstaver as $tecken) {
$var = 'tecken' . ($i + 1);
$$var = $tecken;
$i++;
}
?>
I'd like to end up with as many $tecken variables (With the names $tecken, t$tecken1, $tecken2 etc) as the number of charachters in the input.
All help much appreciated, as always!
You don't need to create separate variables for each letter because you have all the letters in an array. Then you just index into the array to get out each letter.
Here is how I would do it.
//get the word from the form
$word = $_POST['input'];
//split word into characters
$characters = str_split($word);
//suppose the word is "jim"
//this prints out
// j
// i
// m
foreach($characters as $char)
print $char . "\n"
//now suppose you want to change the first letter so the word now reads "tim"
//Access the first element in the array (ie, the first letter) using this syntax
$characters[0] = "t";
I dont think its a good idea, but heres how you do it:
<?php
$input = 'Hello world!';
for($i = 0; $i < strlen($input); $i++) {
${'character' . $i} = $input[$i];
}
why do you want that?
you can just go with:
$word = 'test';
echo $word[2]; // returns 's'
echo $word{2}; // returns 's'
$word{2} = 'b';
echo $word{2}; //returns 'b'
echo $word; // returns 'tebt'
...

Categories