如何从字符串中提取单个字母或数字?

How to extract a single letter or number from a string?

我需要从字符串中提取特定的字母或数字。

<div id="craftysyntax_1" style="float: right;"><script type="text/javascript" src="https://livehelp.clipboards.com/livehelp_js.php?eo=0&amp;department=1&amp;serversession=1&amp;pingtimes=10&amp;dynamic=Y&amp;creditline=W"></script></div>

从这个 divid="craftysyntax_1" 我只想从这个 [=] 中提取数字 1 21=]craftysyntax_1,我正在尝试使用 explode,但它对我不起作用,或者我做错了什么。

这是我试过的方法:

$myString = '<div id="craftysyntax_1" style="float: right;"><script type="text/javascript" src="https://livehelp.clipboards.com/livehelp_js.php?eo=0&amp;department=1&amp;serversession=1&amp;pingtimes=10&amp;dynamic=Y&amp;creditline=W"></script></div>';
            $strArray = explode('craftysyntax_', $myString, 1);
            print_r($myString);

我怎样才能达到我想要的?

preg_match("/craftysyntax_(.*)\" /", $myString, $output_array);
echo $output_array[1];

祝你好运!

您可以使用 regEx 来完成本例中的目标

$myString = '<div id="craftysyntax_123" style="float: right;"><script type="text/javascript" src="https://livehelp.clipboards.com/livehelp_js.php?eo=0&amp;department=1&amp;serversession=1&amp;pingtimes=10&amp;dynamic=Y&amp;creditline=W"></script></div>';
$pttn = '@craftysyntax_(\d{1,})@';
preg_match( $pttn, $myString, $matches );

echo '<pre>',print_r($matches,1),'</pre>';

这将输出:

Array
(
    [0] => craftysyntax_123
    [1] => 123
)

因此您可以使用 $matches[1]

明确定位整数

I want to extract just the number 1 from this craftysyntax_1

使用preg_match函数:

$myString = '<div id="craftysyntax_1" style="float: right;"><script type="text/javascript" src="https://livehelp.clipboards.com/livehelp_js.php?eo=0&amp;department=1&amp;serversession=1&amp;pingtimes=10&amp;dynamic=Y&amp;creditline=W"></script></div>';

preg_match("/id=[\"']craftysyntax_(\d+)[\"']/", $myString, $matches);
$craft_number = $matches[1];

print_r($craft_number);  // 1

你真的shouldn't use regex to try and parse HTML.

替代方案,使用DOMDocument提取你想要的ID:

$str = '<div id="craftysyntax_1" style="float: right;"><script type="text/javascript" src="https://livehelp.clipboards.com/livehelp_js.php?eo=0&amp;department=1&amp;serversession=1&amp;pingtimes=10&amp;dynamic=Y&amp;creditline=W"></script></div>';

$dom = new DOMDocument;
$dom->loadHTML($str);
$src = $dom->getElementsByTagName('div')->item(0);
$attr = $src->attributes->getNamedItem('id')->value;

这将为您提供值 craftysyntax_1。现在您可以轻松获取 last 下划线之后的所有内容,如果它存在:

if (($pos = strrpos($attr, '_')) !== false) {
    echo substr($attr, $pos + 1);
}

尝试使用 preg_match:

$myString = '<div id="craftysyntax_1" style="float: right;"><script type="text/javascript" src="https://livehelp.clipboards.com/livehelp_js.php?eo=0&amp;department=1&amp;serversession=1&amp;pingtimes=10&amp;dynamic=Y&amp;creditline=W"></script></div>';
preg_match("/id=[\"']craftysyntax_(\d+)[\"']/", $myString, $output);
print_r($output);  //Array ( [0] => id="craftysyntax_1" [1] => 1 )
print_r($output[1]);//1