Let's say I have a string like this
I am flying from "Detroit to Vancouver" this July
$string = 'I am flying from "Detroit to Vancouver" this July';
I also have an array of "stopwords
" (words that I'm choosing to remove from the string/strings)
$stopwords = array( "to", "anotherstopword", "andanother" )
Right now I'm just using
$string = str_replace($stopwords, ' ', $string);
This of course gives me string(33) "I am flying from "Detroit Vancouver" this July"
I was thinking about maybe exploding the $string
with a space before the str_replace
, giving me something like
Array
(
[0] => I
[1] => am
[2] => flying
[3] => from
[4] => "Detroit
[5] => to
[6] => Vancouver"
[7] => this
[8] => July
)
Then perhaps removing them from the array, doing the replace, and re-inserting them.. but this seems overkill
I've also thought about using a function like this
function getStringBetween($str, $from, $to, $withFromAndTo = false)
{
$sub = substr($str, strpos($str, $from) + strlen($from), strlen($str));
if ($withFromAndTo)
return $from . substr($sub, 0, strrpos($sub, $to)) . $to;
else
return substr($sub, 0, strrpos($sub, $to));
}
When doing so,
echo '<pre>';
print_r(getStringBetween($string, '"', '"'));
echo '</pre>';
Outputs:
Detroit to Vancouver
And doing some type of ignore condition before the str_replace..
But this fails whenever there are multiple quotations in the string..
Ideally I would like to create a condition to where if the string contains double quotes, to ignore them entirely in the str_replace
process.
I am of course not opposed to using something other than str_replace, like preg_replace, but I do not have enough experience with that to produce a sample for my expected output.
Can anyone think of a good way to ignore stop words/words to be removed before doing the replace?
EDIT:
Code Sample
<?php
$stopwordstest = array( " to ", " a ", " test " );
$string = 'I am flying from "Detroit to Vancouver" this July when the weather is test nice';
var_dump($string);
// as is, without string replace
// string(79) "I am flying from "Detroit to Vancouver" this July when the weather is test nice"
$string = str_replace($stopwordstest, ' ', $string);
echo '<br><br>';
var_dump($string);
// string(71) "I am flying from "Detroit Vancouver" this July when the weather is nice"
// Expected output is:
//
// string(74) "I am flying from "Detroit to Vancouver" this July when the weather is nice"
//
?>
In other words, I'd like the string replacement to go forth as intended, but since the word to
is encapsulated in quotes ("Detroit to Vancouver"
), it should skip this word because it is in quotes.