简体   繁体   English

在第二次出现一个字符之后和最后一次出现相同字符之前使用php返回一个字符串

[英]Returning a string after the second occurrence of a character and before the last occurrence of the same character with php

I have several strings similar to the following: ORG-000012 – Name of variation – Quantity: 12 Pack – $14.95 我有几个类似于以下的字符串:ORG-000012 - 变异名称 - 数量:12包 - 14.95美元

I need to remove all characters before the second hyphen and after the last hyphen with php. 我需要在第二个连字符之前和最后一个连字符之后删除所有字符。 For example, the string above needs to return as: Name of variation – Quantity: 12 Pack 例如,上面的字符串需要返回为:变体名称 - 数量:12包

I have tried to use strpos and substr but I can't seem to get the correct setup. 我试过使用strpos和substr,但我似乎无法得到正确的设置。 Please help! 请帮忙!

Just use explode() , splitting by . 只需使用explode() ,按分割即可。 Then, get the second and third elements: 然后,获取第二个和第三个元素:

<?php
$description = "ORG-000012 – Name of variation – Quantity: 12 Pack – $14.95";
$descriptionArray = explode(" – ", $description);
$finalDescription = $descriptionArray[1]." – ".$descriptionArray[2];
var_dump($finalDescription); // string(39) "Name of variation – Quantity: 12 Pack"

Demo 演示

Or, if the number of elements in between is variable, array_shift() and array_pop() the array to remove the first and last elements: 或者,如果其间的元素数是可变的,则array_shift()array_pop()数组将删除第一个和最后一个元素:

<?php
$description = "ORG-000012 – Name of variation – Quantity: 12 Pack – $14.95";
$descriptionArray = explode(" – ", $description);
array_pop($descriptionArray);
array_shift($descriptionArray);
var_dump($descriptionArray);

Demo 演示

You can find the position of the first occurrence of - char using strpos and find the position of the last occurrence ot it using strrpos : 您可以使用strpos找到第一次出现的字符- char的位置,并使用strrpos查找最后一次出现的位置:

$s = 'ORG-000012 - Name of variation - Quantity: 12 Pack - $14.95';
$sub = substr($s,strpos($s, '-')+1, strrpos($s, '-')-strlen($s));
print $sub; // or print trim($sub) to remove the whitespaces

What it does is, it will print a substrinig of $s starting from one character after the first occurrence of - character, and omitting characters from last occurrence of - by passing a negative value (difference of total length of the string and position of last occurrence of - character) as length to substr . 它所做的是,它会打印的substrinig $s的第一次出现之后,从一个字符开始-字符,并忽略从最后出现的字符-通过传递一个负值字符串的总长度和位置的最后的(差出现-字符)作为substr长度。

Please note, this will print the space character before the last - as well, so you might want to trim the result as well. 请注意,这将在最后一个之前打印空格字符-因此您可能还想trim结果。

Is possible with a reg expr, try with: 可以使用reg expr,尝试使用:

preg_match(
    '/(?<=\s–\s)(.*)(?:\s–\s)[^\s]+$/',
    'ORG-000012 – Name of variation – Quantity: 12 Pack – $14.95',
    $matches
);
echo $matches[1]; //Name of variation – Quantity: 12 Pack 

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

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