Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

substring in php whether words is first or last in string

Tags:

php

substr

strpos

I have this piece of PHP to find a campaign name in string and then use substr on the occurrence of the campaign name.

 $chars = array("æ", "ø", "å");
 $replace = array("ae", "oe", "aa");

 $dash = strpos(utf8_decode($campaign["campaign_name"]), "Studiepakke");
 $decoded_name = utf8_decode($campaign["campaign_name"]);
 $id_name = str_replace($chars, $replace, trim(strtolower(substr($decoded_name, 0, ($dash-2)))));

 $lpage_pos = strripos($id_name, $_GET["lpage"]);
 $short_name = strtolower(utf8_decode($campaign["adset_name"]));
 $dash_pos = strpos($short_name, " - ");

$campaign["campaign_name"] can look like "aalborg - studiepakke", but it can also be "studiepakke - aalborg"

How can I use substr and strpos so it is unimportant whether "Studiepakke" is at the beginning or at the end of the string. My end result will always be

"aalborg".

like image 950
Morten Hagh Avatar asked Nov 27 '25 04:11

Morten Hagh


1 Answers

If I get it right you may want to split strings where the dash is. For this purpose, use

$substrings = explode(" - ", $string);

This will give you an array of substrings, you can then check which one is the searched one.

You could also use string replace to replace the unwanted part with an empty string.

str_replace()
str_ireplace() // case insensitive
like image 143
Barthy Avatar answered Nov 28 '25 18:11

Barthy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!