从字符串中删除不必要的字

时间:2016-09-07 11:25:50

标签: php

我想从字符串中删除一些单词,以使我的图片alt标签更具相关性。

问题是,如果我有这样的阶段:

barack obama at a restaurant in venice

我希望退出:

barack obama restaurant venice

但我拥有的是:

barack obamaa restaurantvenice

代码: -

$a = array( ' at ', ' in ', ' arriving ', ' a ', ' leaving ', ' walks ', ' walking ', ' her ' );
$str = 'barack obama at a restaurant in venice';
echo str_replace($a,"",$str);

如果我在数组中使用没有空格的单词,结果会非常糟糕:

brck obm resturnt venice

有什么想法吗?

1 个答案:

答案 0 :(得分:5)

您必须在""内添加一个空格,如下所示: -

echo str_replace($a," ",$str);

点击此处: -

<?php

$a = array( ' at ', ' in ', ' arriving ', ' a ', ' leaving ', ' walks ', ' walking ', ' her ' );
$str = 'barack obama at a restaurant in venice';
echo str_replace($a," ",$str);

输出: - https://eval.in/636890