I have the following string:
$thetextstring = "jjfnj 948"
At the end I want to have:
echo $thetextstring; // should print jjf-nj948
So basically what am trying to do is to join the separated string then separate the first 3 letters with a -.
So far I have
$string = trim(preg_replace('/s+/', ' ', $thetextstring));
$result = explode(" ", $thetextstring);
$newstring = implode('', $result);
print_r($newstring);
I have been able to join the words, but how do I add the separator after the first 3 letters?
Use a regex with preg_replace function, this would be a one-liner:
^.{3}\K([^\s]*) *
Breakdown:
^ # Assert start of string
.{3} # Match 3 characters
\K # Reset match
([^\s]*) * # Capture everything up to space character(s) then try to match them
PHP code:
echo preg_replace('~^.{3}\K([^\s]*) *~', '-$1', 'jjfnj 948');
PHP live demo
Without knowing more about how your strings can vary, this is working solution for your task:
Pattern:
~([a-z]{2}) ~ // 2 letters (contained in capture group1) followed by a space
Replace:
-$1
Demo Link
Code: (Demo)
$thetextstring = "jjfnj 948";
echo preg_replace('~([a-z]{2}) ~','-$1',$thetextstring);
Output:
jjf-nj948
Note this pattern can easily be expanded to include characters beyond lowercase letters that precede the space. ~(\S{2}) ~
You can use str_replace to remove the unwanted space:
$newString = str_replace(' ', '', $thetextstring);
$newString:
jjfnj948
And then preg_replace to put in the dash:
$final = preg_replace('/^([a-z]{3})/', '\1-', $newString);
The meaning of this regex instruction is:
from the beginning of the line: ^
capture three a-z characters: ([a-z]{3})
replace this match with itself followed by a dash: \1-
$final:
jjf-nj948
$thetextstring = "jjfnj 948";
// replace all spaces with nothing
$thetextstring = str_replace(" ", "", $thetextstring);
// insert a dash after the third character
$thetextstring = substr_replace($thetextstring, "-", 3, 0);
echo $thetextstring;
This gives the requested jjf-nj948
You proceeding is correct. For the last step, which consists in inserting a - after the third character, you can use the substr_replace function as follows:
$thetextstring = 'jjfnj 948';
$string = trim(preg_replace('/\s+/', ' ', $thetextstring));
$result = explode(' ', $thetextstring);
$newstring = substr_replace(implode('', $result), '-', 3, false);
If you are confident enough that your string will always have the same format (characters followed by a whitespace followed by numbers), you can also reduce your computations and simplify your code as follows:
$thetextstring = 'jjfnj 948';
$newstring = substr_replace(str_replace(' ', '', $thetextstring), '-', 3, false);
Visit this link for a working demo.
Oldschool without regex
$test = "jjfnj 948";
$test = str_replace(" ", "", $test); // strip all spaces from string
echo substr($test, 0, 3)."-".substr($test, 3); // isolate first three chars, add hyphen, and concat all characters after the first three
Related
my string may be like this:
# *lorem.jpg,,, ip sum.jpg,dolor ..jpg,-/ ?
in fact - it is a dirty csv string - having names of jpg images
I need to remove any non-alphanum chars - from both sides of the string
then - inside the resulting string - remove the same - except commas and dots
then - remove duplicates commas and dots - if any - replace them with single ones
so the final result should be:
lorem.jpg,ipsum.jpg,dolor.jpg
I firstly tried to remove any white space - anywhere
$str = str_replace(" ", "", $str);
then I used various forms of trim functions - but it is tedious and a lot of code
the additional problem is - duplicates commas and dots may have one or more instances - for example - .. or ,,,,
is there a way to solve this using regex, pls ?
List of modeled steps following your words:
Step 1
"remove any non-alphanum chars from both sides of the string"
translated: remove trailing and tailing consecutive [^a-zA-Z0-9] characters
regex: replace ^[^a-zA-Z0-9]*(.*?)[^a-zA-Z0-9]*$ with $1
Step 2
"inside the resulting string - remove the same - except commas and dots"
translated: remove any [^a-zA-Z0-9.,]
regex: replace [^a-zA-Z0-9.,] with empty string
Step 3
"remove duplicates commas and dots - if any - replace them with single ones"
translated: replace consecutive [,.] as a single
instance
regex: replace (\.{2,}) with .
regex: replace (,{2,}) with ,
PHP Demo:
https://onlinephp.io/c/512e1
<?php
$subject = " # *lorem.jpg,,, ip sum.jpg,dolor ..jpg,-/ ?";
$firstStep = preg_replace('/^[^a-zA-Z0-9]*(.*?)[^a-zA-Z0-9]*$/', '$1', $subject);
$secondStep = preg_replace('/[^a-z,A-Z0-9.,]/', '', $firstStep);
$thirdStepA = preg_replace('(\.{2,})', '.', $secondStep);
$thirdStepB = preg_replace('(,{2,})', ',', $thirdStepA);
echo $thirdStepB; //lorem.jpg,ipsum.jpg,dolor.jpg
Look at
https://www.php.net/manual/en/function.preg-replace.php
It replace anything inside a string based on pattern. \s represent all space char, but care of NBSP (non breakable space, \h match it )
Exemple 4
$str = preg_replace('/\s\s+/', '', $str);
It will be something like that
Can you try this :
$string = ' # *lorem.jpg,,,, ip sum.jpg,dolor .jpg,-/ ?';
// this will left only alphanumirics
$result = preg_replace("/[^A-Za-z0-9,.]/", '', $string);
// this will remove duplicated dot and ,
$result = preg_replace('/,+/', ',', $result);
$result = preg_replace('/\.+/', '.', $result);
// this will remove ,;. and space from the end
$result = preg_replace("/[ ,;.]*$/", '', $result);
Hi i'm trying to replace all digits or numbers in a string except digits after dash by blank space
For example I have this :
$string = "1234 Example-1234";
And I want to have only "Example-1234"
I tried preg_replace('/\-?\d+/','',$string); but even digits after dash are replaced
Edited: Thanks everyone i tried all of your answers and it works well !
If you want to just skip all digits preceded with - and remove all others, use
'~-\d+(*SKIP)(*F)|\d+~'
See the regex demo
Note you would like to trim the result or add \s* around \d+ pattern.
Pattern details:
-\d+(*SKIP)(*F) - match -, 1+ digits and skip this match
| - or
\d+ - 1 or more digits
See the PHP demo:
$str = '1234 Example-1234';
$res = preg_replace('/-\d+(*SKIP)(*F)|\s*\d+/', '', $str);
echo trim($res); // => Example-1234
The solution using regex negative lookbehind assertion (?<!a)b:
$str = "1234 Example-1234";
$str = preg_replace('/(?<![0-9-])\d+/', '', $str);
print_r($str);
The output:
Example-1234
Because you are looking for words that contain a dash, you can achieve this by to splitting the string via spaces, loop through the array values until you find a string with a dash, and then output from there onwards.
$string = "1234 Example-1234";
$words = explode(" ", $string);
foreach($words as $word) {
if (strpos($word, '-') !== false) {
echo $word;
break; // delete this line if there are multiple instances of words with dashes in your string
}
}
This will output Example-1234.
You can see a working example here
ONLINE Regex tester : https://regex101.com/r/ykUWfM/3
<?php
$string = "1234 Example-1234";
echo preg_replace('/-(\d+)/','',$string);
?>
OUTPUT: before - convert into string
1234 Example
NOTE: Before - its get the string before dash -
OR
Demo: https://regex101.com/r/ykUWfM/2
<?php
$string = "1234 Example-1234";
echo preg_replace('/(?<![0-9-])\s*\d+/','',$string);
?>
OUTPUT:
Example-1234
How can i remove part of string from example:
##lang_eng_begin##test##lang_eng_end##
##lang_fr_begin##school##lang_fr_end##
##lang_esp_begin##test33##lang_esp_end##
I always want to pull middle of string: test, school, test33. from this string.
I Read about ltrim, substr and other but I had no good ideas how to do this. Becouse each of strings can have other length for example :
'eng', 'fr'
I just want have string from middle between ## and ##. to Maye someone can help me? I tried:
foreach ($article as $art) {
$title = $art->titl = str_replace("##lang_eng_begin##", "", $art->title);
$art->cleanTitle = str_replace("##lang_eng_end##", "", $title);
}
But there
##lang_eng_end##
can be changed to
##lang_ger_end##
in next row so i ahvent idea how to fix that
If your strings are always in this format, an explode way looks easy:
$str = "##lang_eng_begin##test##lang_eng_end## ";
$res = explode("##", $str)[2];
echo $res;
You may use a regex and extract the value in between the non-starting ## and next ##:
$re = "/(?!^)##(.*?)##/";
$str = "##lang_eng_begin##test##lang_eng_end## ";
preg_match($re, $str, $match);
print_r($match[1]);
See the PHP demo. Here, the regex matches a ## that is not at the string start ((?!^)##), then captures into Group 1 any 0+ chars other than newline as few as possible ((.*?)) up to the first ## substring.
Or, replace all ##...## substrings with `preg_replace:
$re = "/##.*?##/";
$str = "##lang_eng_begin##test##lang_eng_end## ";
echo preg_replace($re, "", $str);
See another demo. Here, we just remove all non-overlapping substrings beginning with ##, then having any 0+ chars other than a newline up to the first ##.
Trying to remove the hyphens which come before start of the alphabet and after end of a alphabet, but not to lose the hyphens in between.
Example
this the string i have
---this-is-my-page--
output: this-is-my-page
Note( no of hyphen are different on each request, it may be many in numbers)
2. Example
how to do this,
---this-is-page---
i need to replace the hyphen which is in between string with empty space. but not to loose to the hyphens in start and end.
Use trim function it will work for any number of -(hyphen) at start or end of your string,
$str = "---this-is-my-page---";
echo $str = trim($str,"-");
Edit:
And than use str_replace,
$str = str_replace("-"," ",$str);
DEMO.
Use trim($string, $trimCharacters):
trim — Strip whitespace (or other characters) from the beginning and end of a string
<?php
$str = '---this-is-my-page---';
var_dump( trim($str, '-') ); //string(15) "this-is-my-page"
?>
DEMO
If you only want to replace the hyphens inside the string (and not in the start/end) you can use regex:
/^(-+)(.*?)(-+)$/
..and replace it with (first group)(second group with hyphens replaced)(third group).
In code:
<?php
$str = '---this-is-my-page---';
$str = preg_replace_callback('/^(-+)(.*?)(-+)$/', function($matches) {
return $matches[1] . str_replace('-', ' ', $matches[2]) . $matches[3];
}, $str);
var_dump( $str ); //string(21) "---this is my page---"
?>
DEMO
echo trim( "---this-is-my-page---","-");
trim removes a character at the and and begin
I want to remove any type of special characters in a string like this:
This is, ,,, *&% a ::; demo + String. +
Need to**#!/// format:::::
!!! this.`
Output Required:
This is a demo String Need to format this
How to do this using REGEX?
Check for any repeated instance of a non-number, non-letter character and repeat with a space:
# string(41) "This is a demo String Need to format this"
$str = trim( preg_replace( "/[^0-9a-z]+/i", " ", $str ) );
Demo: http://codepad.org/hXu6skTc
/ # Denotes start of pattern
[ # Denotes start of character class
^ # Not, or negative
0-9 # Numbers 0 through 9 (Or, "Not a number" because of ^
a-z # Letters a through z (Or, "Not a letter or number" because of ^0-9
] # Denotes end of character class
+ # Matches 1 or more instances of the character class match
/ # Denotes end of pattern
i # Case-insensitive, a-z also means A-Z
Use:
preg_replace('#[^a-zA-Z0-9 ]#', '', $yourString);
If characters are not alphabet, numbers or space, it is replaced with empty string.
Example:
$yourString = 'This is, ,,, *&% a ::; demo + String. + Need to**#!/// format::::: !!! this.`';
$newStr = preg_replace('#[^a-zA-Z0-9 ]#', '', $yourString);
echo $newStr;
Result:
This is a demo String Need to format this
So you can allow more characters if you want by putting them in:
[^a-zA-Z0-9 ]
Note: Also if you don't want to allow multiple spaces between words (though they wont be shown when output in browser), you need to use this instead:
preg_replace('#[^a-zA-Z0-9]+#', ' ', $yourString);
echo preg_replace('/[^a-z]+/i', ' ', $str);
// This is a demo String Need to format this
$string = preg_replace('/[^a-z]+/i', ' ', $string);
You may also want to allow ' in your character class to have conjunctions like don't not be turned into don t:
$string = preg_replace('/[^a-z\']+/i', ' ', $string);
You might also want to trim it afterwards to remove leading and trailing whitespace:
$string = trim(preg_replace('/[^a-z\']+/i', ' ', $string));