Reputation: 97
I have a form that takes in a users input and puts it in an array, the user then chooses a word they want to find in said array. Thereafter the array is checked to see what each index of the word is as well as each occurrence of the word in the text.
So if you write the string "What is what" and want to find the word "what" it will say that the position of the word is "0 and 2" whereas I'd like it to say "1 and 3". How do I go about this?
Here's the code:
<form action="sida3.php" method="post">
Text: <textarea name="textarea"></textarea>
<br> Search word: <input type="text" name="search">
<br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
if(isset($_POST['submit'])){
$parts = explode(" ", $_POST['textarea']);
$strName = $_POST['search'];
print_r ($parts);
echo '<br>';
foreach($parts as $item) {
if ($item == $strName) {
$counter++;
}
}
echo "The word $strName can be found at: ";
echo implode(' ', array_keys($parts, $strName));
echo "<br>";
echo "The word $strName was found $counter times";
}
Upvotes: 0
Views: 73
Reputation: 23958
You can use array_combine to combine a range from 1 to count of the array with the values.
$str = "This is a string.";
$arr = explode(" ", $str);
$range = range(1,count($arr)); // creates a range from 1 -> count of $arr
$new = array_combine($range, $arr); // sets the range as the key and $arr as the value
var_dump($new);
All done without looping.
$str = "This is a car. Automobile (car) is another word for it. You can also add a hashtag, #car";
$find = "car";
$count = substr_count($str, $find);
$str = preg_replace("/[^a-zA-Z 0-9]/", "", $str);
$arr = explode(" ", $str);
$range = range(1,count($arr));
$new = array_combine($range, $arr);
$positions = array_keys(array_intersect($new, [$find]));
echo $find . " was found " . $count . " times. At positions: " . implode(", ", $positions);
Just looping and matching with == will only find one car in this string.
Upvotes: 1
Reputation: 41820
You can map +1
over the array keys before imploding. I also suggested another way to find the search term and count the occurrences, if you're interested in that, but map will work with the way you're currently doing it as well.
$found = array_intersect($parts, [$strName]);
echo "The word $strName can be found at: ";
echo implode(' ', array_map(function($x) { return $x + 1; }, array_keys($found)));
echo "<br>";
echo "The word $strName was found ". count($found) ." times";
Upvotes: 1
Reputation: 78994
I'm not sure what you're doing with the foreach
or if that's where you want to create the positions, but:
foreach($parts as $pos => $item) {
if ($item == $strName) {
$result[] = $pos + 1;
}
}
Then just:
echo implode(' ', $result);
Upvotes: 1