Laravel how to replace a words in string - laravel

I am trying to change words in string, I know laravel Str::replace() function but it converts if you write exact word. This is what i want to do :
$string = " this is #username and this is #username2"
I want to find usernames which starts with "#" and make them like below, i want to add <strong> html tag them :
$newstring = " this is <strong>#username</strong> and this is <strong>#username2</strong>"
I couldnt find the way to change dynamic value on str replace.
Thanks

Use preg_replace
$string = 'this is #username and this is #username2';
$newString = preg_replace('/(\#\w+)/', '<strong>$1</strong>', $string);
Docs: https://www.php.net/manual/en/function.preg-replace.php

Related

Create title slug + random string Laravel 7

I would like to create a slug that combines the title + a random string in Laravel.
I tried this, but nothing, in the second case it does nothing but combine the character string with the title.
Str::slug(request('title'), '-', Str::random());
or
Str::slug(request('title'), Str::random());
I would like something like this:
this-is-an-example-title-Jfij4jio4523q234
Double-check the method signature from https://laravel.com/docs/7.x/helpers#method-str-slug (and deeper at https://github.com/laravel/framework/blob/7.x/src/Illuminate/Support/Str.php#L552)
To be explicit, the second parameter of the method is the character used to replace whitespace, and the third parameter refers to the locale to use when generating the slug. That means you need your string to be fully composed before passing it to the method.
Assuming you want your slug joined by a - then something like this is what you want:
$value = request('title') . ' ' . Str::random();
$slug = Str::slug($value); // optionally Str::slug($value, '-'); to explicitly define the join
Str::Slug() has been defined as:
slug(string $title, string $separator = '-', string $language = 'en')
The third param can be seen as language with default value: en.
Str::slug($request->input('title').Str::random(40), '-');
I hope this helps.

How to remove amp; from URL

I am getting a URL that contains amp;. Is there any way to remove this as currently I tried URLDecode function, but It's not working. Do I need to remove It using simple string replacement or Is there any better way to do this?
As #Lankymart pointed out URLDecode only works on URL-encoded characters (%26), not on HTML entities (&). Use a regular string replacement to change the HTML entity & into a literal ampersand:
url = Replace(url, "&", "&")
In Angular I added amp; to the params names
this.activatedRoute.queryParams.subscribe(params => {
this.user_id = params['user_id'];
this.practice_id = params['amp;practice_id'];
this.patient_id = params['amp;patient_id'];
});

How do I use gsub to search and replace using a regex?

I want to filter tags out of a description string, and want to make them into anchor tags. I am not able to return the value of the tag.
My input is:
a = "this is a sample #tag and the string is having a #second tag too"
My output should be:
a = "this is a sample #tag and the string is having a #second tag too"
So far I am able to do some minor stuff but I am not able to achive the final output. This pattern:
a.gsub(/#\S+/i, "<a href='/tags/\0'>\0</a>")
returns:
"this is a sample <a href='/tags/\u0000'>\u0000</a> and the string is having a <a href='/tags/\u0000'>\u0000</a> tag too"
What do I need to do differently?
You can do it like this:
a.gsub(/#(\S+)/, '\0')
The reason why your replacement doesn't work is that you must use double escape when you are between double quotes:
a.gsub(/#(\S+)/, "<a href='/tags/\\1'>\\0</a>")
Note that the /i modifier is not needed here.
You need to give gsub a block if you want to do something with the match from the regex:
a.gsub(/#(\S+)/i) { "<a href='/tags/#{$1}'>##{$1}</a>" }
$1 is a global variable that Ruby automatically fills with the first capture block in the matched string.
Try this:
a.gsub(/(?<a>#\w+)/, '\k<a>')

XQuery looking for text with 'single' quote

I can't figure out how to search for text containing single quotes using XPATHs.
For example, I've added a quote to the title of this question. The following line
$x("//*[text()='XQuery looking for text with 'single' quote']")
Returns an empty array.
However, if I try the following
$x("//*[text()=\"XQuery looking for text with 'single' quote\"]")
It does return the link for the title of the page, but I would like to be able to accept both single and double quotes in there, so I can't just tailor it for the single/double quote.
You can try it in chrome's or firebug's console on this page.
Here's a hackaround (Thanks Dimitre Novatchev) that will allow me to search for any text in xpaths, whether it contains single or double quotes. Implemented in JS, but could be easily translated to other languages
function cleanStringForXpath(str) {
var parts = str.match(/[^'"]+|['"]/g);
parts = parts.map(function(part){
if (part === "'") {
return '"\'"'; // output "'"
}
if (part === '"') {
return "'\"'"; // output '"'
}
return "'" + part + "'";
});
return "concat(" + parts.join(",") + ")";
}
If I'm looking for I'm reading "Harry Potter" I could do the following
var xpathString = cleanStringForXpath( "I'm reading \"Harry Potter\"" );
$x("//*[text()="+ xpathString +"]");
// The xpath created becomes
// //*[text()=concat('I',"'",'m reading ','"','Harry Potter','"')]
Here's a (much shorter) Java version. It's exactly the same as JavaScript, if you remove type information. Thanks to https://stackoverflow.com/users/1850609/acdcjunior
String escapedText = "concat('"+originalText.replace("'", "', \"'\", '") + "', '')";!
In XPath 2.0 and XQuery 1.0, the delimiter of a string literal can be included in the string literal by doubling it:
let $a := "He said ""I won't"""
or
let $a := 'He said "I can''t"'
The convention is borrowed from SQL.
This is an example:
/*/*[contains(., "'") and contains(., '"') ]/text()
When this XPath expression is applied on the following XML document:
<text>
<t>I'm reading "Harry Potter"</t>
<t>I am reading "Harry Potter"</t>
<t>I am reading 'Harry Potter'</t>
</text>
the wanted, correct result (a single text node) is selected:
I'm reading "Harry Potter"
Here is verification using the XPath Visualizer (A free and open source tool I created 12 years ago, that has taught XPath the fun way to thousands of people):
Your problem may be that you are not able to specify this XPath expression as string in the programming language that you are using -- this isn't an XPath problem but a problem in your knowledge of your programming language.
Additionally, if you were using XQuery, instead of XPath, as the title says, you could also use the xml entities:
"" for double and &apos; for single quotes"
they also work within single quotes
You can do this using a regular expression. For example (as ES6 code):
export function escapeXPathString(str: string): string {
str = str.replace(/'/g, `', "'", '`);
return `concat('${str}', '')`;
}
This replaces all ' in the input string by ', "'", '.
The final , '' is important because concat('string') is an error.
Well I was in the same quest, and after a moment I found that's there is no support in xpath for this, quiet disappointing! But well we can always work around it!
I wanted something simple and straight froward. What I come with is to set your own replacement for the apostrophe, kind of unique code (something you will not encounter in your xml text) , I chose //apos// for example. now you put that in both your xml text and your xpath query . (in case of xml you didn't write always we can replace with replace function of any editor). And now how we do? we search normally with this, retrieve the result, and replace back the //apos// to '.
Bellow some samples from what I was doing: (replace_special_char_xpath() is what you need to make)
function repalce_special_char_xpath($str){
$str = str_replace("//apos//","'",$str);
/*add all replacement here */
return $str;
}
function xml_lang($xml_file,$category,$word,$language){ //path can be relative or absolute
$language = str_replace("-","_",$language);// to replace - with _ to be able to use "en-us", .....
$xml = simplexml_load_file($xml_file);
$xpath_result = $xml->xpath("${category}/def[en_us = '${word}']/${language}");
$result = $xpath_result[0][0];
return repalce_special_char_xpath($result);
}
the text in xml file:
<def>
<en_us>If you don//apos//t know which server, Click here for automatic connection</en_us> <fr_fr>Si vous ne savez pas quelle serveur, Cliquez ici pour une connexion automatique</fr_fr> <ar_sa>إذا لا تعرفوا أي سرفير, إضغطوا هنا من أجل إتصال تلقائي</ar_sa>
</def>
and the call in the php file (generated html):
<span><?php echo xml_lang_body("If you don//apos//t know which server, Click here for automatic connection")?>

Is there a Joomla function to generate the 'alias' field?

I'm writing my own component for Joomla 1.5. I'm trying to figure out how to generate an "alias" (friendly URL slug) for the content I add. In other words, if the title is "The article title", Joomla would use the-article-title by default (you can edit it if you like).
Is there a built-in Joomla function that will do this for me?
Line 123 of libraries/joomla/database/table/content.php implements JFilterOutput::stringURLSafe(). Pass in the string you want to make "alias friendly" and it will return what you need.
If you are trying to generate an alias for your created component it is very simple. Suppose you have click on save or apply button in your created component or suppose you want to make alias through your tile, then use this function:
$ailias=JFilterOutput::stringURLSafe($_POST['title']);
Now you can insert it into database.
It's simple PHP.
Here is the function from Joomla 1.5 source:
Notice, I have commented the two lines out. You can call the function like
$new_alias = stringURLSafe($your_title);
function stringURLSafe($string)
{
//remove any '-' from the string they will be used as concatonater
$str = str_replace('-', ' ', $string);
$str = str_replace('_', ' ', $string);
//$lang =& JFactory::getLanguage();
//$str = $lang->transliterate($str);
// remove any duplicate whitespace, and ensure all characters are alphanumeric
$str = preg_replace(array('/\s+/','/[^A-Za-z0-9\-]/'), array('-',''), $str);
// lowercase and trim
$str = trim(strtolower($str));
return $str;
}

Resources