PHP在描述中的#之后获取字符[关闭]

How can I make each product identification number mentioned in the below description into variables, excluding the # pulling them from the description in PHP?

Two 9-dram clear styrene tubes with snap-on caps, 1 x 2-3/4″ I.D. (25.2 x 68mm), are supplied as containers. Additional or replacement tubes #8909 are available.

As a safety precaution, BioQuip recommends using the #1135Y HEPA filter with this aspirator.

Also see #1135X aspirator syringe bulb. It allows users to aspirate specimens without inhaling particulate matter.

One could use this regular expression (regex):

/#(\w+)/

along with preg_match_all() which performs a global search for data matching a regex, and stores what it finds in an array, as follows:

<?php

$str = "Two 9-dram clear styrene tubes with snap-on caps, 1 x 2-3/4″ I.D. (25.2 x 68mm), are supplied as containers. Additional or replacement tubes #8909 are available.

As a safety precaution, BioQuip recommends using the #1135Y HEPA filter with this aspirator.

Also see #1135X aspirator syringe bulb. It allows users to aspirate specimens without inhaling particulate matter.";

$pat = "/#(\w+)/";
if ( preg_match_all( $pat, $str, $matches )) {
  $popped = array_pop( $matches );
  list( $alpha, $beta, $gamma ) = $popped;
  echo "The IDs are as follows:

$alpha
$beta
$gamma
";  
}


See demo

This regex specifies a hashtag followed by parentheses to "remember" one or more word characters, i.e. numeric or alphabetical data. By enclosing this expression with parentheses, the hashtag will be excluded and the remaining data stored in $matches[1]. Once $matches contains data, you are done unless you wish to utilize $matches[1] to create three unique variables and optionally display their values.

You could dispense with using a regex and use the following code with the above-indicated value of $str:

<?php
$ids=[];
$a = explode("#",$str);
array_shift( $a );
$ids = array_map( function( $e ) {
                  return explode(" ",$e)[0];
                  },$a);

print_r($ids);

See demo

By avoiding preg_match_all(), the second solution may offer the advantage of better performance. Alternately, you can split the array returned by explode() into a list that only includes relevant information, and then create an array of the list variables for array_map(), as follows:

<?php

$ids=[];
list(,$a,$b,$c) = explode( "#",$str );
$ids = array_map(function( $e ) {
                  return explode(" ",$e )[0];
                  },[ $a,$b,$c ]);

print_r( $ids );

See demo

Solution

Use Regex. This regex I wrote (\#.+?) (note the space at end) matches the product id numbers. Try it out here. To use the regex with PHP use preg_match_all:

preg_match_all

(PHP 4, PHP 5, PHP 7) preg_match_all — Perform a global regular expression match

Description

int preg_match_all ( string $pattern , string $subject [, array &$matches [, int $flags = PREG_PATTERN_ORDER [, int $offset = 0 ]]] )

Code

<?php
    $pattern = "/(\#.+?) /";
    $string = "Two 9-dram clear styrene tubes with snap-on caps, 1 x 2-3/4″ I.D. (25.2 x 68mm), are supplied as containers. Additional or replacement tubes #8909 are available. As a safety precaution, BioQuip recommends using the #1135Y HEPA filter with this aspirator. Also see #1135X aspirator syringe bulb. It allows users to aspirate specimens without inhaling particulate matter.";
    preg_match_all($pattern, $string, $matches);
    print_r($matches[0]);
?>

Output

Array
(
    [0] => #8909
    [1] => #1135X
    [2] => #1135Y
)

Once, you have the array, you can access the codes, that were found, by grabbing them from $matches[0]. For example to print the first match, just do this:

$matches[0][0]

The second match:

$matches[0][1]

and, if you want to get really fancy you can print it out into a table:

<?php
    $pattern = "/(\#.+?) /";
    $string = "Two 9-dram clear styrene tubes with snap-on caps, 1 x 2-3/4″ I.D. (25.2 x 68mm), are supplied as containers. Additional or replacement tubes #8909 are available. As a safety precaution, BioQuip recommends using the #1135Y HEPA filter with this aspirator. Also see #1135X aspirator syringe bulb. It allows users to aspirate specimens without inhaling particulate matter.";
    preg_match_all($pattern, $string, $matches);

    echo "<table border='1' style='border-collapse: 
    collapse;border-color: silver;'>";  
    echo "<tr style='font-weight: bold;'>";  
    echo "<td width='150' align='center'>Product Codes</td>";  
    echo "</tr>";

    foreach ($matches[0] as $match) 
     { 
      echo '<td width="150" align=center>' . $match . '</td>';
      echo '</tr>';
     }
?>

This would output:

Product code table

Try it out

PHP Sandbox

Without regex, you could split the string by space and add a substring of each word beginning with # to an array of results.

foreach (explode(' ', $description) as $word) {
    if ($word[0] == '#') $products[] = substr($word, 1);
}

I think it's safe to assume this will be slower than regex, though.