简体   繁体   中英

I want to extract a part of the string from a string using regular expression

I have the variable $state="Mississippi Alabama Texas Massachusetts Kansas". I wanna find the word which contains xas in the end and store this word in a array.I am trying for it, but no results:

<?php
$states="Mississippi Alabama Texas Massachusetss Kansas";
$str="/xa$/";
$string="";
$ee=preg_match( "/xas$/",$str,$matches);
echo $ee;
echo $matches;

You can use word break \\b instead end-of-string ( $ ) and you should also include the other characters of the word you try to match (with \\w* ):

$states="Mississippi Alabama Texas Massachusetss Kansas";
preg_match("/\w*xas\b/", $states, $matches);
print_r($matches);

output:

Array( [0] => "Texas" )

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