在PHP中如何从整数中提取字符并以整个单词返回它

huangapple go评论67阅读模式
英文:

How to extract a character from integer and return it in entire word in PHP

问题

我已使用此代码提取整数。我需要返回整个单词。

$str = 'Hello World - A45565656676 - Test Case';
preg_match_all('!\b\w+\d+\w+\b!', $str, $matches);
print_r($matches);

输出:

Array ( [0] => Array ( [0] => A45565656676 ) )
英文:

I have used this code to extract the integer. I need to return the entire word.

$str = 'Hello World - A45565656676 - Test Case';
preg_match_all('!\d+!', $str, $matches);
print_r($matches);

OUTPUT:

Array ( [0] => Array ( [0] => 45565656676 ) )

I need this

Array ( [0] => A45565656676 )

答案1

得分: 1

我使用了这个正则表达式

第一个捕获组 ([A-Z]\d+)

  • 匹配在以下列表中的单个字符 [A-Z]
  • A-Z 匹配在 A (索引 65) 和 Z (索引 90) 之间的单个字符(区分大小写)
  • \d+ 匹配一个数字(等同于 [0-9])
  • + 量词 — 匹配一次或多次,尽可能多次匹配,按需回退(贪婪模式)

此外,在这里不需要使用 preg_match_all(),可以使用 preg_match() 示例

$str = 'Hello World - A45565656676 - Test Case';
preg_match('/([A-Z]\d+)/', $str, $matches);
print_r($matches[0]);
英文:

I used this regex

([A-Z]\d+)

1st Capturing Group ([A-Z]\d+)

  • Match a single character present in the list below [A-Z]
  • A-Z a single character in the range between A (index 65) and Z (index 90) (case sensitive)
  • \d+ matches a digit (equal to [0-9])
  • + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)

In addition, you do not need preg_match_all() here, use preg_match() EXAMPLE

$str = 'Hello World - A45565656676 - Test Case';
preg_match('/([A-Z]\d+)/', $str, $matches);
print_r($matches[0]);

答案2

得分: 1

你可以用不同的方法来做:

$str = "Hello World - A45565656676 - Test Case";
print_r(explode(" - ", $str)[1]); // A45565656676

了解更多:https://www.php.net/manual/pt_BR/function.explode.php

英文:

You can do it in a differen method:

$str = "Hello World - A45565656676 - Test Case";
print_r(explode(" - ", $str)[1]); // A45565656676

Learn more: https://www.php.net/manual/pt_BR/function.explode.php

答案3

得分: 0

在这种情况下,您可以使用explode()

Explode:

explode()函数将字符串拆分为数组。

注意:“separator”参数不能是空字符串。

注意:此函数是二进制安全的。

<?php
    $str = 'Hello World - A45565656676 - Test Case';

    $matches=explode("-",$str)[1];
    print_r($matches);
?>
英文:

<p>You can use <code> explode()</code> in this case.</p>

<p><strong>Explode:</strong></p>

<p>The <code> explode()</code> function breaks a string into an array.</p>

<p><strong>Note:</strong>&nbsp;The &quot;separator&quot; parameter
cannot be an empty string.</p>

<p><strong>Note:</strong>&nbsp;This function is binary-safe.</p>

<pre><code>&lt;?php
$str = 'Hello World - A45565656676 - Test Case';

$matches=explode(&quot;-&quot;,$str)[1];
print_r($matches);

?&gt;</code></pre>

huangapple
  • 本文由 发表于 2020年1月6日 21:41:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/59613175.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定