English 中文(简体)
计数字符串中的 php 数组发生数组
原标题:Counting php array occurrences in a string
  • 时间:2012-05-22 01:48:47
  •  标签:
  • php

我有一个字符串和一个数值阵列, 我想检查一个数组中的项目有多少倍出现在字符串中 。

这是最快的方法吗?

$appearsCount = 0;

$string = "This is a string of text containing random abc def";
$items = array("abc", "def", "ghi", "etc");

foreach($items as $item)
{
    $appearsCount += substr_count($string, $item);
}

echo "The item appears $appearsCount times";
最佳回答

您可能会发现正则表达式有用 :

$items = array( abc ,  def ,  ghi ,  etc );
$string =  This is a string of text containing random abc def ;

$appearsCount = count(preg_split( / .implode( | , $items). / , $string)) - 1;

当然, 您必须注意不要使正则表达式无效 。 (例如, 您需要正确避免在 < code>$itms 中包含正则表达式中特殊字符的值 。 )

这是 non 与您的多个子字符串计数完全相同的东西, 因为重叠的项目不会以正则表达式拆分两次计算 。

问题回答

最快速, 可能 - 至少您在任意输入时不可能更快。 然而, 请注意您可能不是< a href=>" http:// php. net/ manual/ en/ office. substr-count. php" rel = "nofollow" > 完全正确 :

$appearsCount = 0;

$string = "How many times is  cac  in  cacac ?";
$items = array("cac");

foreach($items as $item)
{
    $appearsCount += substr_count($string, $item);
}

echo "The item appears $appearsCount times";




相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签