英文:
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> The "separator" parameter
cannot be an empty string.</p>
<p><strong>Note:</strong> This function is binary-safe.</p>
<pre><code><?php
$str = 'Hello World - A45565656676 - Test Case';
$matches=explode("-",$str)[1];
print_r($matches);
?></code></pre>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论