简体   繁体   English

PHP:如何检查字符串的大写特定部分?

[英]PHP: How to check for and uppercase specific parts of a string?

How to format specific parts of a string? 如何格式化字符串的特定部分?

In this case, I have a form that asks users for an address, and it posts to php as a variable that I catch with $_POST , and turn it into a variable which I output like the following to make it look cleaner: 在这种情况下,我有一个向用户询问地址的表单,它以$_POST捕获的变量的形式发布到php,然后将其转换为变量,输出如下所示,以使其看起来更干净:

$receive_address = ucwords(strtolower(str_replace('.','',$_POST['send_address'])));

The address would be entered into the form like this... 地址将以这种形式输入...

100 john st., toronto, on 约翰街100号,多伦多,在

...and be outputted as this... ...并以此输出...

100 John St, Toronto, On 约翰街100号,多伦多,上

If I enter 100 john st., toronto , on, or 100 john st., toronto, ontario , I want the final result to be this: 如果输入100 john st., toronto100 john st., toronto, ontario ,我希望最终结果是这样的:

100 John St, Toronto, ON 安大略省多伦多市约翰街100号

Literally the only difference is that the final result will conclude with the province in 2 letters, capitalized. 从字面上看,唯一的区别是最终结果将以全省2个字母大写。

I want to take it a step further and check to see if there is an "On" in there at the end, and if there isn't to add it, and if there is, to capitalize both letters. 我想更进一步,检查结尾处是否有“ On”,是否没有添加,以及是否有两个字母都大写。

Is this possible, and how would this work? 这可能吗,这将如何工作?


Here's my attempt at figuring this out: 这是我试图弄清楚的尝试:

function findProvCode($address_data) {
    $prov_codes = array('NL','PE','NS','NB','QC','ON',' MB','SK','AB','BC','YT','NT','NU')
    if (stripos($address_data, $prov_codes)) {
        // still need to find out which of the prov codes it is...
        // $specify_code = something to do with finding out which code this address already had
        str_replace('$address_data',strtoupper($specify_code),$address_data);
    } 
}

Here's a PHP sandbox of where I'm at so far... someone had posted an answer with some ideas but deleted it (assuming because it didn't work the way they had intended), those ideas were useful though: http://sandbox.onlinephpfunctions.com/code/36f1e07e2e52573e230da4dda49320c564a818cd 这是到目前为止我所处的PHP沙箱...有人发布了一些想法的答案,但删除了它(假设因为它没有按照他们的预期目的工作),这些想法还是有用的: http:/ /sandbox.onlinephpfunctions.com/code/36f1e07e2e52573e230da4dda49320c564a818cd

The workflow seems simple... 工作流程似乎很简单...

1 - check for province or province code 1-检查省或区号

2 - if province code, uppercase it 2-如果是省区代码,请大写

3 - if whole word, change to province code and uppercase province code 3-如果是整个单词,请更改为省区代码和大写的省区代码

Just not sure how to do this. 只是不确定如何执行此操作。


I know this really isn't that important in reality... I just want to learn how to manipulate a string this way. 我知道实际上这并不重要……我只想学习如何以这种方式操作字符串。

Do this at the end of your code: 在代码末尾执行此操作:

$address_string = "100 John St, Toronto, On";

$address_array = explode(',', $address_string);
array_push($address_array, strtoupper(array_pop($address_array)));
$address_string = implode(',', $address_array);

OR , if you prefer a function: ,如果您更喜欢函数:

function CapProvCode($address_string){
    $address_array = explode(',', $address_string);
    array_push($address_array, strtoupper(array_pop($address_array)));
    return implode(',', $address_array);
}

Where $address_string is the string which the two last letters will be capitalized. $ address_string是最后两个字母将大写的字符串。

I've tried them here and I got the following output after a echo $address_string; 我在这里尝试过,在echo $address_string;之后得到以下输出echo $address_string;

100 John St, Toronto, ON 安大略省多伦多市约翰街100号


Explaning what happened: 解释发生了什么:

The explode function breaks the string everytime it finds a ',' (delimiter) and return the pieces into an array. explode函数每次找到“,”(定界符)时都会中断字符串,并将片段返回到数组中。 So, after the first line, $address_array is: 因此,在第一行之后,$ address_array为:

Array
(
    [0] => 100 John St
    [1] =>  Toronto
    [2] =>  On
)

On second line we will analyse piece after piece. 在第二行,我们将逐个分析。 The most inside nest, array_pop , take out the last item of $address_array and we got this 最里面的嵌套array_pop取出$address_array的最后一项,我们得到了

second line in progress 第二行正在进行中

array_push($address_array, strtoupper(" On"));

print_r() of $address_array at this moment 此时的$ address_array的print_r()

Array
(
    [0] => 100 John St
    [1] =>  Toronto
)

Now the function strtoupper() capitalize the string " On". 现在,函数strtoupper()将字符串“ On”大写。 On the outter nest, array_push insert the string capitalized at the last position of $address_array : 在外部嵌套上, array_push$address_array的最后一个位置插入大写的字符串:

print_r() of $address_array after second line is evaluated 计算第二行后$ address_array的print_r()

Array
(
    [0] => 100 John St
    [1] =>  Toronto
    [2] =>  ON
)

Then, on third line, implode make the oposit of explode, join all pieces of an array into a string and separating them by ','. 然后,在第三行,进行爆破 ,将数组的所有部分连接成一个字符串,并用“,”将其分开。 That's it! 而已!


Solving with Regular Expressions 用正则表达式求解

To work with the possibility of a string like 100 John St, Toronto, On, Canada , you have to deal with Regular Expressions . 要使用诸如100 John St, Toronto, On, Canada这样的字符串,您必须处理正则表达式 They are really not easy to understand and even harder to write, but definetly worth to learn how and when to use them. 它们确实不容易理解,甚至更难编写,但是绝对值得学习如何以及何时使用它们。 Regex are useful when you are dealing with string patterns. 在处理字符串模式时,正则表达式很有用。

Php has a native function to replace strings using regex : preg_replace() . Php具有本机功能,可以使用regex替换字符串: preg_replace() Take a look at this code, it should do the trick: 看一下这段代码,它应该可以解决问题:

$address_string[] = "100 John St, Toronto, On, Canada";
$address_string[] = "100 John St, Toronto, on, Canada";
$address_string[] = "100 John St, Toronto, On";
$address_string[] = "100 John St, Toronto, on";

foreach($address_string as $value){
    echo preg_replace('/, [A-za-z]{2}(,|$)/e', 'strtoupper("$0")', $value);
    echo "<br>";
}

I executed it and the output is: 我执行了它,输出是:

100 John St, Toronto, ON, Canada 加拿大安大略省多伦多市约翰街100号

100 John St, Toronto, ON, Canada 加拿大安大略省多伦多市约翰街100号

100 John St, Toronto, ON 安大略省多伦多市约翰街100号

100 John St, Toronto, ON 安大略省多伦多市约翰街100号

I hope it works for all cases. 我希望它适用于所有情况。 Don't give up easily when trying to understand regex, they are really hard. 在尝试了解正则表达式时不要轻易放弃,它们确实很难。 This can help you. 可以为您提供帮助。

You can use "relations map" array in such manner array('toronto' =>'ON', ...) to define which province the certain town is related to: 您可以通过以下方式使用“关系图”数组array('toronto' =>'ON', ...)来定义特定城镇与哪个省有关:

function findProvCode($address_data) {
    $prov_codes = array('toronto' =>'ON', 'NL','PE','NS','NB','QC','MB','SK','AB','BC','YT','NT','NU');
    $words = explode(" ", ucwords($address_data));
    $last_index = count($words) - 1;

    if (in_array(strtoupper($words[$last_index]), $prov_codes)) {
        $words[$last_index] = strtoupper($words[$last_index]);        
    } elseif (array_key_exists(strtolower($words[$last_index]), $prov_codes)) {
        $words[] = $prov_codes[strtolower($words[$last_index])];
    }
    return implode(" ", $words);
}

echo findProvCode("100 john st., toronto, on") . "<br>";
echo findProvCode("100 john st., toronto");

The output: 输出:

100 John St., Toronto, ON
100 John St., Toronto ON

Since you specifically asked about string manipulation, this is one way to do it using (mostly) string functions. 由于您专门询问过字符串操作,因此这是使用(主要是)字符串函数进行操作的一种方法。

$codes = array('NL','PE','NS','NB','QC','ON','MB','SK','AB','BC','YT','NT','NU');

$province = strtoupper(substr($address, -2));        // take last 2 chars and convert to UC
if (in_array($province, $codes)) {                   // try to find it in the codes array
    $address = substr($address, 0, -2) . $province;  // replace last 2 chars with UC version
}

Not only string functions because I don't think there really is a better way than in_array to verify that a string is part of a certain set of strings. 不仅字符串函数,因为我认为没有比in_array更好的方法来验证字符串是否是特定字符串集的一部分。 You could do something like 你可以做类似的事情

if (strpos('NL|PE|NS|NB|QC|ON|MB|SK|AB|BC|YT|NT|NU', $province) !== false) { ...

but regardless of the delimiter used, matching an arbitrary string against a longer string instead of an array of strings can theoretically yield false positives. 但无论使用哪种定界符,理论上将任意字符串与更长的字符串而不是字符串数组进行匹配都可以产生误报。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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