astrstr

Snippet: function astrstr()

Following up on the astrpos() function, here is an astrstr() function:

Source Code - astrstr()

<?php
 
/**
 * function astrstr()
 *
 * Function to find the first instance of any needle from an array of strings 
 * within a string
 * 
 *
 * @author      Stuart Jones <stuart@random-tweak.co.uk>
 * @copyright   Copyright 2008 Stuart Jones
 * @version    08.11.25
 * @license   <a href="http://www.gnu.org/licenses/gpl.html<br />
" title="http://www.gnu.org/licenses/gpl.html<br />
">http://www.gnu.org/licenses/gpl.html<br />
</a> * 
 * @param    string          $haystack
 * @param    array&lt;string&gt;   $needles
 * @param   [int          $offset]
 * @param   [int          $flags]
 */
 
 
// define constants for function flags 
if (!defined('ASTR_NEEDLE_ORDER')) { define('ASTR_NEEDLE_ORDER', 1); }

Documentation - astrstr()

Description

  • int astrstr ( string $haystack, array $needles [, $offset [, int $flags ] ] )
    Returns the first instance of either the first needle found in the haystack, or the first instance of a needle in the haystack.

Parameters

  • haystack

    The string to search in

  • needle

    An array of strings to search in the haystack for

  • offset

Examples - astrstr()

<?php
 
include "astrstr.php";
 
$needles = array(
  'apple',
  'banana',
 'pear',
 'orange',
);
 
$haystack = 'The fruiterer has some bananas and apples today. Unfortunately, there are no oranges, but the pears will be in tomorrow.';
 
// this will return the string from the first instance of 'banana' 
// the first needle in the haystack
echo astrstr($haystack, $needles) . "\r\n";
 
// this will return the string upto the first instance of 'banana' 
// the first needle in the haystack
echo astrstr($haystack, $needles, 0, ASTR_BEFORE_NEEDLE) . "\r\n";