简体   繁体   中英

PHP preg_match function get phone number from string

Here is my PHP code. I'm needing a regular expression to get my desired output.

$str = 'abc:123,phoneNumber:631 741-4498, fdsfdsf, hgjhtg,juiy';

Expected Output: 631741-4498

$str = 'abc:123,phoneNumber:+123 423, fdsfdsf, hgjhtg,juiy';

Expected Output: +123 423

$str = 'abc:123,phoneNumber:+(123) 423-727, fdsfdsf, hgjhtg,juiy';

Expected Output: +(123) 423-727

Here's what I've tried

$str = 'abc:123,phoneNumber:631 741-4498, fdsfdsf, hgjhtg,juiy';
$str = str_replace(" ","",$str);
preg_match('/phoneNumber:\s*(.*)/', $str, $matches);

Change your regular expression to /(\\d+ \\d+\\-\\d+)/

<?php

$str = 'abc:123,phoneNumber:631 741-4498, fdsfdsf, hgjhtg,juiy';
preg_match('/(\d+ \d+\-\d+)/', $str, $matches);

print_r($matches[0]);

Live preview

Edit

Change your regular expression to /phoneNumber:[a-zA-Z0-9\\ \\+\\-(\\(\\))]+/

<?php

$str = 'abc:123,phoneNumber:631 741-4498, fdsfdsf, hgjhtg,juiy';
preg_match('/phoneNumber:[a-zA-Z0-9\ \+\-(\(\))]+/', $str, $matches);

print_r( str_replace("phoneNumber:", "", $matches[0]) );

Live preview

Live preview - all outputs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM