如何在字符串中找到多个变量?

时间:2011-12-17 21:06:23

标签: php

我有一个脚本检查变量$hello,看它是否包含“粉红色”,“蓝色”和“红色”。对于它包含的每个变量,一些文本将添加到字符串$finalstring

有更简单的方法吗?

$hello = "pink*blue*red*orange";
$finalstring = "";

if (strpos($hello, "pink") == true) {
    $finalstring .= "_pink";
}

if (strpos($hello, "blue") == true) {
    $finalstring .= "_blue";
}

if (strpos($hello, "red") == true) {
    $finalstring .= "_red";
}

echo $finalstring; // output: _pink_blue_red

5 个答案:

答案 0 :(得分:3)

$finalstring = '';

$items = array('pink', 'blue', 'red');
foreach($items as $item)
{
   if(strpos($hello, $item) !== false)
   {
       $finalstring .= '_' . $item;
   }
}

答案 1 :(得分:0)

您可以使用要检查的所有值($types)创建一个数组,遍历所有值并检查它们是否可以在您的字符串中找到...

$hello = "pink*blue*red*orange";
$finalstring = "";
$types = array('pink', 'blue', 'red');
foreach ($types as $type) {
  if (stristr($hello, $type)) {
    $finalstring .= '_' . $type;
  }
}

答案 2 :(得分:0)

<?php
function yourFunction($input, $keywords){
    $result = "";

    for($i = 0; $i < count($keywords); $i++){
        if(strpos($input, $keywords[$i]) !== FALSE)
            $result .= "_" . $keywords[$i];
    }

    return $result;
}

$finalString = yourFunction("pink*blue*red*orange", Array("pink", "blue", "red"));

echo $finalString;
?> 

答案 3 :(得分:0)

$hello = "pink*blue*red*orange";
$finalstring = "";
getString($finalstring, "pink");
getString($finalstring, "blue");
getString($finalstring, "red");
echo $finalstring;

    function getString($mainString, $word){
        if (strpos($mainString, $word) == true) {
           $finalstring .= "_".$word;
         }
     }

答案 4 :(得分:0)

使用正则表达式

$hello = "pink*blue*red*orange";
$colors = array('pink', 'blue', 'orange'); 
if(!preg_match_all(sprintf("/%s/", join('|', $colors)), $hello, $match))
{
    die('not found any color');
}
$finalstring = '_'. join('_', $match[0]);
echo $finalstring; // _pink_blue_orange